Submitted By: Mohit Garg
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
/* Java Factorial Using Recursion Example This Java example shows how to generate factorial of a given number using recursive function. */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class JavaFactorialUsingRecursion { public static void main(String args[]) throws NumberFormatException, IOException{ System.out.println("Enter the number: "); //get input from the user BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int a = Integer.parseInt(br.readLine()); //call the recursive function to generate factorial int result= fact(a); System.out.println("Factorial of the number is: " + result); } static int fact(int b) { if(b <= 1) //if the number is 1 then return 1 return 1; else //else call the same function with the value - 1 return b * fact(b-1); } } /* Output of this Java example would be Enter the number: 5 Factorial of the number is: 120 */ |
very nice
it could be with a Scanner, much simplier
Scanner number=new Scanner(System.in);
Int num;
num=number.nextInt();
Nice one ….good attempt
The problem with this brute force attempt that I’ve found is that it won’t work with large n. for n>39 there’s an overflow and the function starts returning negative number. If you added a check for negative inputs to return 0, which is an invalid value of the factorial function you’ll get exactly that since there are recursive calls being made.
The problem is integer range is small,if u use BigInteger to solve the overflow problem
Also saying that n< 1 will return 1 is incorrect. The factorial function does NOT cover negative integers by definition.
//if b<0 then use the abs() method,that will be ok
if(b<0) {
b = Math.abs(b);
return -b*fac(b-1);
} ;
if(b<=1)
return 1;
else{
return b*fac(b-1);
}