|
| 1 | +/** |
| 2 | + * **Factorial Finder** - The Factorial of a positive integer, n, |
| 3 | + * is defined as the product of the sequence n, n-1, n-2, ...1 and the |
| 4 | + * factorial of zero, 0, is defined as being 1. |
| 5 | + * Solve this using both loops and recursion. |
| 6 | + */ |
| 7 | + |
| 8 | +import java.io.*; |
| 9 | +import java.math.*; |
| 10 | + |
| 11 | +public class Factorial { |
| 12 | + |
| 13 | + private static BigInteger calcRecursive(int n){ |
| 14 | + if (n==0) |
| 15 | + return BigInteger.valueOf(1); |
| 16 | + else if (n==1) |
| 17 | + return BigInteger.valueOf(1); |
| 18 | + else |
| 19 | + return calcRecursive(n-1).multiply(BigInteger.valueOf(n)); |
| 20 | + } |
| 21 | + |
| 22 | + private static BigInteger calcLoop(int n) { |
| 23 | + BigInteger result = BigInteger.valueOf(1); |
| 24 | + for(int i=n; i>1; i--) |
| 25 | + { |
| 26 | + result = result.multiply(BigInteger.valueOf(i)); |
| 27 | + } |
| 28 | + return result; |
| 29 | + } |
| 30 | + |
| 31 | + public static void main(String args[]) throws IOException{ |
| 32 | + System.out.println("Factorial calculator. Enter n: "); |
| 33 | + int userAns=10; |
| 34 | + BigInteger result; |
| 35 | + try(BufferedReader br = new BufferedReader(new InputStreamReader(System.in))){ |
| 36 | + userAns = Integer.parseInt(br.readLine()); |
| 37 | + |
| 38 | + |
| 39 | + System.out.print("Recurcive? (y/N): "); |
| 40 | + if (br.readLine().toLowerCase().equals("y")) { |
| 41 | + result = calcRecursive(userAns); |
| 42 | + } else { |
| 43 | + result = calcLoop(userAns); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + System.out.printf("Result: %d! = ",userAns); |
| 48 | + System.out.println(result.toString()); |
| 49 | + } |
| 50 | +} |
0 commit comments