Search code examples
javaiterationfactorial

Factorial iteration java


poCould anyone explain this piece of code to me?? Its a power function using iteration

  public static int iterate(int a, int n) 
{
    int i ;
    int result = 1 ;

    for(i = 0 ; i < n ; i++){
        result = result*a ;              
    }
    return result ;

}

Solution

  • It helps to know the definition of factorial:

    0! = 1
    1! = 1
    2! = 2*1 = 2
    3! = 3*2*1 = 6
    4! = 4*3*2*1 = 24
    n! = n*(n-1)*(n-2)*...*2*1
    

    See the pattern?

    1. Start with result = 1
    2. Loop and multiply by index
    3. Return result

    What you posted looks more like a^n = a*a*a...*a to me, not factorial.