Code in Java
Create a file called Factorial.java. This file should have the
following method:
public static long calculate(long n) Factorial.calculate should
recursively calculate n!, where 0! = 1 and n! = n(n−1)!. The method
should also print out an error and exit if n < 0 or n > 20,
since factorial is not defined for negative numbers and will overflow
Java’s long variable with larger numbers (if we used an int, it
would overflow even sooner!). Inside Factorial.java, also include a
main method which runs a couple of tests on
Factorial.calculate:
java Factorial Factorial.calculate(0) returned 1. Test passed!
Factorial.calculate(5) returned 120. Test passed!
public class Factorial { public static long calculate(long n) { if (n == 0) { return 1; } else { return n * calculate(n-1); } } public static void main(String[] args) { long result = Factorial.calculate(0); System.out.println("Factorial.calculate(0) returned " + result); if (result == 1) { System.out.println("Test passed!"); } result = Factorial.calculate(5); System.out.println("Factorial.calculate(5) returned " + result); if (result == 120) { System.out.println("Test passed!"); } } }
Get Answers For Free
Most questions answered within 1 hours.