• + 1 comment

    I think using tail recursion will be good choice as it reduces the number of call stack. Below code does not require more than one call stack as result of calculated value is passed along with recursion call. Hence there is no wait for any call stack.

    public class Solution {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int result = factorial(n, 1);
        System.out.println(result);
    }
    
    private static int factorial(int n, int currVal){
        if(n == 0 || n == 1){
            return currVal;
        }
        return factorial(n-1, n * currVal);
    }