diff --git a/code/languages/Java/Factorial.java b/code/languages/Java/Factorial.java new file mode 100644 index 0000000000..e6d7cea29e --- /dev/null +++ b/code/languages/Java/Factorial.java @@ -0,0 +1,35 @@ +import java.util.Scanner; + +class Factorial { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + System.out.print("Enter a number to find its factorial: "); + int n = sc.nextInt(); + + // Try to calculate the factorial of n, catch any exceptions that are thrown. + try { + System.out.println(n + "! = " + factorial(n)); + } catch (Exception e) { + System.out.println(e.getMessage()); + } + sc.close(); + } + + /** + * This method recursively calculates the factorial of an integer. + * @param n An integer we are finding the factorial of. + * @return The factorial of `n`. + * @throws Exception If `n` is negative. + */ + public static int factorial(int n) throws Exception { + + // Check that factorial is non-negative, throw an expection if not. + if (n < 0) { + throw new Exception("Factorial of negative number is not possible"); + } else if (n == 0 || n == 1) { // Base cases, no need to recurse further. + return 1; + } else { // Non-negative n and not at a base case, so multiply n by the factorial of n-1 and return it. + return n * factorial(n - 1); + } + } +} \ No newline at end of file diff --git a/code/languages/Java/README_Factorial.md b/code/languages/Java/README_Factorial.md new file mode 100644 index 0000000000..a0514a1934 --- /dev/null +++ b/code/languages/Java/README_Factorial.md @@ -0,0 +1,23 @@ +# Recursive Factorial + +This program shows how we can calculate any integer factorial recursively. A factorial is defined +as $n! = (n) \cdot (n-1) \cdot (n-2) \cdots (2) \cdot (1)$. So, we can rewrite this as $n! = (n) \cdot (n-1)!$ +with base cases of $1! = 1$ and $0! = 1$. This is our recursive definition and is how we implement +the code. + +## Features + +- **Factorial Calculation**: The program calculates the factorial of a non-negative integer. +- **Exception Handling**: Throws an exception when trying to compute the factorial of a negative number.\ + +## Getting Started + +### Running the Program + +1. Clone this repository to your local machine. +2. Compile and run the `Factorial` class. + +### Warning + +Be aware that factorials grow extremely quickly. So, there is a limit to how large the input +$n$ can be without causing overflow, leading to an incorrect answer.