Sunday, June 12, 2011

Factorial in java

Method 1 Using a for loop

Well the simplest is to use a for loop to find the factorial of a number.

static long factorial(int factorial) {

  int fact = 1;

  for (int i = factorial; i > 0; i--) {
   fact *= i;
  }

  return fact;
 }


Method 2 : Using recursion

public static long factorial( int n )
    {
        if( n <= 1 )     // base case
            return 1;
        else
            return n * factorial( n - 1 );
    }

No comments:

Post a Comment