Create a file called Factorial.java. This file should have the following method:
ID: 3875093 • Letter: C
Question
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 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 . calculate(0) returned 1. Test passed! Factorial. calculate (5) returned 120. Test passed! (Obviously, if these tests do not return 1 and 120 respectively, the tests should fail and print out an appropriate message.)Explanation / Answer
/**
* class for Factorial
*
* @author
*
*/
public class Factorial {
/**
* @param args
*/
public static void main(String[] args) {
// tests
System.out.println("Factorial.calculate(0) return "
+ Factorial.calculate(0));
System.out.println("Factorial.calculate(5) return "
+ Factorial.calculate(5));
System.out.println("Factorial.calculate(-2) return "
+ Factorial.calculate(-2));
System.out.println("Factorial.calculate(-2) return "
+ Factorial.calculate(-2));
System.out.println("Factorial.calculate(21) return "
+ Factorial.calculate(21));
}
/**
* function to calculate factorial of n value using recursions
*
* @param n
* @return
*/
public static long calculate(long n) {
// invalid check
if (n < 0 || n > 20) {
System.out.println("invalid n value 0<=n<=20 ");
return -1;
} else if (n == 0)
return 1;
else if (n > 1) {
// calling function recursively
return (n * calculate(n - 1));
}
return 1;
}
}
OUTPUT:
Factorial.calculate(0) return 1
Factorial.calculate(5) return 120
invalid n value 0<=n<=20
Factorial.calculate(-2) return -1
invalid n value 0<=n<=20
Factorial.calculate(-2) return -1
invalid n value 0<=n<=20
Factorial.calculate(21) return -1
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.