Factorial!

Getting this question for a whiteboard problem is fun. It allows you to give your interviewer a second long “Are you serious?” look and then turning to the white-board and knocking it out in silence. Of course if you get it wrong you get to wish that you can just melt into the carpet.

The factorial of a number is simply a number multiplied by each integer smaller than itself, all the way down to 1.


public static int factorial(int number){

    if (number < 1){
        return 0;
    }

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

    return fact;

}

Of course, you will probably be asked if you can do this recursively too, so you turn around and and scribble this on the white-board


public static int factorial(int number){

    if (number < 1){
        return 0;
    }

    if (number==1){
        return 1;
    }

    return number*factorial(number-1);

}

Leave a Reply

Your email address will not be published. Required fields are marked *