March 10, 2024

Java Problem Solution: Calculate the Factorial of a Number in Java (Loop and Recursion)


public class FactorialCalculator {
    public static void main(String[] args) {
        int numberToCalculate = 5; // Change this to test different numbers.
        try {
            long factorialWithLoop = calculateFactorialWithLoop(numberToCalculate);
            System.out.println("Factorial of " + numberToCalculate + " using loop: " + factorialWithLoop);
            long factorialWithRecursion = calculateFactorialWithRecursion(numberToCalculate);
            System.out.println("Factorial of " + numberToCalculate + " using recursion: " + factorialWithRecursion);
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
    public static long calculateFactorialWithLoop(int number) {
    	// Time complexity O(n)
        if (number < 0) {
            throw new IllegalArgumentException("Factorial is not defined for negative numbers.");
        }
        long factorial = 1;
        for (int i = 2; i <= number; i++) {
            factorial *= i;
        }
        return factorial;
    }
    
    public static long calculateFactorialWithRecursion(int number) {
        if (number < 0) {
            throw new IllegalArgumentException("Factorial is not defined for negative numbers.");
        }
        if (number == 0 || number == 1) {
            return 1;
        }
    	// Time complexity O(n)        
        return number * calculateFactorialWithRecursion(number - 1);
    }
}

Want 1 to 1 personalized Java training? Email me at isingh30 AT gmail please. View my following video

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.