This code snippet calculates the factorial of a number up to 20. Because of the large numbers it can't go higher then 20, 21 factorial is: 51.090.942.171.709.440.000. There are two methods in this code, one for calculating it with recursion and one non-recursive.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| public class Factorial { public static void main(String[] args) { System.out.println(factorialRecursion( 20 )); System.out.println(factorial( 20 )); } public static long factorialRecursion( long l) { if (l < 2 ) return 1 ; else return l * factorialRecursion(l - 1 ); } public static long factorial( int fact) { long result = 1 ; for ( int i = 1 ; i <= fact; ++i) { result *= i; } return result; } } |
Output:
2432902008176640000
2432902008176640000
2432902008176640000
2432902008176640000
Comments
Post a Comment