Please help me on this problem, I give a lifesaver ratingeverytime(because you a
ID: 3617482 • Letter: P
Question
Please help me on this problem, I give a lifesaver ratingeverytime(because you are a lifesaver!)
Write a program to compute the factorial of any given number.Use a recursive method to compute the values. In general, factorial(n) is computed recursively as follows:
factorial(n) = n * factorial (n-1); //and
factorial(0) = 1; //stopping condition
Forexample:
factorial(3) = 3 * factorial (3 - 1) = 3 * factorial (2);à = 3 * 2 * 1 * 1 = 6
factorial(2) = 2 * factorial (2 – 1) = 2 * factorial(1);
factorial(1) = 1 * factorial (1 – 1) = 1 * factorial(0);
factorial(0) = 1; //now backtrack and compute the above values for factorial(1),factorial(2), and factorial(3).
Once a number is entered by theuser, the program should display a table for all numbers below theentered number and computes all of their factorials. Forexample, if the user entered n=5, the table will look asfollows:
Number Factorial
5 120
4 24
3 6
2 2
1 1
0 1
Explanation / Answer
import java.util.*;
class factorial { public static void main(String args[]) { int num; Scanner kb=new Scanner(System.in); System.out.print("Enter Number for Factorial: "); num=kb.nextInt();
System.out.println("Number Factorial"); for(int v=num;v>=1;v--) { int fac=factorial(v); System.out.println(v+" "+fac); } } public static int factorial(int n) { if(n==0) return 1; else return n*factorial(n-1); } }
import java.util.*;
class factorial { public static void main(String args[]) { int num; Scanner kb=new Scanner(System.in); System.out.print("Enter Number for Factorial: "); num=kb.nextInt();
System.out.println("Number Factorial"); for(int v=num;v>=1;v--) { int fac=factorial(v); System.out.println(v+" "+fac); } } public static int factorial(int n) { if(n==0) return 1; else return n*factorial(n-1); } }