Javascript, calculating factorial

The factorial of a given positive integer is the product of all positive integers less than and equal to the given positive integer. For example, the factorial of 5!=1*2*3*4*5=120
The javascript code snippet below demonstrates two methods of calculating the factorial of a number, recursive and iterative.

function recursiveFactorial(num)
{
	if(num < 0) {
		return -1;
	}
    else if(num === 0) {
    	return 1;
    } else {
    	return num * recursiveFactorial(num-1);
    }
}

function iterativeFactorial(num)
{
    if (num < 0) {
        return -1;
    }
    else if (num === 0) {
        return 1;
    }

    var factorial = num;
    num = num-1;
    while (num > 1) {
        factorial = factorial * num;
        num = num -1;
    }
    return factorial;
}

console.log( "The factorial of 5 is:", recursiveFactorial( 5 ) );
console.log( "The factorial of 5 is:", iterativeFactorial( 5 ) );

Output:

The factorial of 5 is: 120
The factorial of 5 is: 120

Search within Codexpedia

Custom Search

Search the entire web

Custom Search