Thursday, July 23, 2015

Iterative and Recursive Factorial Functions in C++

Factorial function is defined as a function which multiplies a given number by every number below it until 1.

For example 5!= 5*4*3*2*1=120.

In C++, factorial function can be implemented in an iterative or recursive way.

For big numbers, return value of factorial functions are declared as unsigned long long.


#include <iostream>
using namespace std;

unsigned long long iterativeFactorial( const unsigned int& value )
{
    unsigned long long result=1;
    unsigned long long i=1;
    while(i<=value)
    {
        result *= i++;
    }

    return result;
}

unsigned long long recursiveFactorial( const unsigned int& value )
{
    if( value == 1 || value == 0 )
        return 1;
    return value*recursiveFactorial(value-1);
}

int main()
{
    const unsigned long value = 20;
    unsigned long long iterativeFactorialResult = iterativeFactorial( value );
    cout << "Iterative Factorial Result : "<< iterativeFactorialResult << endl;

    unsigned long long recursiveFactorialResult = recursiveFactorial( value );
    cout << "Recursive Factorial Result : "<< recursiveFactorialResult << endl;

    return 0;
}

Both factorial functions in C++ source code were tested with the same value = 20 and the following result is achieved.


No comments:

Post a Comment