In: Computer Science
Use Java for the following;
Part 1
n!= n * (n –1)* (n–2)* ...* 3 * 2 * 1
For example, 5! = 5 * 4 * 3 * 2 * 1 = 120
Write a function called factorial that takes as input an integer. Your function should verify that the input is positive (i.e. it is greater than 0). Then, it should compute the value of the factorial using a for loop and return the value. In main, display a table of the integers from 0 to 30 along with their factorials. At some point around 15, you will probably see that the answers are not correct anymore. Think about why this is happening.
/*Make sure you hit like if solution works for you else comment in the comment section*/
public class Factorial {
public static void main(String[]args) {
for(int i=0;i<31;i++) {
System.out.println("Factorial of " + i + ": " + factorial(i));
}
}
private static int factorial(int num) {
int fact = 1;
if(num < 0) {
System.out.println("Number should be greater than 0");
return -1;
}
if(num == 0 || num == 1) return 1;
for(int i = num; i > 0; i--) {
fact = fact * i;
}
return fact;
}
}
It will start giving wrong factorial after 12, it is because factorial of 13 goes out of range of an int data type. If you will use long instead of int you will get correct factorial upto value 20 since it's range is greater than int data type.