C++: Factorial

Bjarne-stroustrup
 

The Factorial Function of a positive integer, n, is defined as the product of the sequence n, n-1, n-2, …1 and the factorial of zero, 0, is defined as being 1.

Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative n errors is optional.

The C versions work unchanged with C++, however, here is another possibility using the STL and boost:

#include <boost/iterator/counting_iterator.hpp>
#include <algorithm>

int factorial(int n)
{
	// last is one-past-end
	return std::accumulate(boost::counting_iterator<int>(1), boost::counting_iterator<int>(n+1), 1, std::multiplies<int>());
}

Iterative

This version of the program is iterative, with a do-while loop.

long long int Factorial(long long int m_nValue)
{
	long long int result=m_nValue;
	long long int result_next;
	long long int pc = m_nValue;
	do
	{
		result_next = result*(pc-1);
		result = result_next;
		pc--;
	}while(pc>2);
	m_nValue = result;
	return m_nValue;
}

SOURCE

Content is available under GNU Free Documentation License 1.2.