i really need help writting this code The factorial of a nonnegative integer n i
ID: 3813441 • Letter: I
Question
i really need help writting this code
The factorial of a nonnegative integer n is written n! ( pronounced "n factorial") and is defined as follows: n!= n x (n-1) x (n-2) x.....x 1 ( for values of n greater than or equal to 1) and n!=1 ( for n=0). for example 5!= 5*4*3*2*1 which is 120....... computes and prints its factorial if the number is larger than 8..... computes and prints the square of the factorial value for the input number if the input number is smaller or equal to 8. for example if you input 5, the output should be 120*120= 14400.....
Explanation / Answer
Please find the required program and output below: Please find the comments against each line for the description:
import java.util.Scanner;
class Test {
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number: ");
int n = scanner.nextInt(); //read the input number from user
int fact = factorial(n); //find the factorial of the number
if(n > 8){ //if n is greater than 8, then print factorial
System.out.println(n+"! = "+fact);
}else { //if n is less than or equal to 8, then print the square of the factorial
System.out.println(fact+" * "+fact+" = "+(fact*fact));
}
}
//function to find the factorial of a number
public static int factorial(int n) {
if(n==0||n==1) //if n is 0 or 1, then return 1
return 1;
else //else return this number * factorial of (this number - 1). Note: This will execute till n<=2
return n * factorial(n-1);
}
}
------------------------------------------------------
OUTPUT:
Enter the number:
5
120 * 120 = 14400
Enter the number:
9
9! = 362880
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.