Skip to content

added recursive factorial function in java #6802

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions code/languages/Java/Factorial.java
Original file line number Diff line number Diff line change
@@ -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);
}
}
}
23 changes: 23 additions & 0 deletions code/languages/Java/README_Factorial.md
Original file line number Diff line number Diff line change
@@ -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.