factorial int - Java java.lang

Java examples for java.lang:int

Description

factorial int

Demo Code


//package com.java2s;

public class Main {
    public static int factorial(int n) {
        return factorial(n, 1);
    }/*from   w  w  w.j a  v  a2  s .c o  m*/

    private static int factorial(int n, int multiplier) {
        if (multiplier <= 0) {
            throw new RuntimeException("zero multipler detected");
        }

        // 1! and 0! both produce 1
        if (n <= 1) { //this will be the same as (n * n-1 * ..... * 2 ) * 1, everything inside the bracket represent the multiplier value 
            return multiplier;
        }

        return factorial(n - 1, multiplier * n);
    }
}

Related Tutorials