Factorial: Difference between revisions

Content added Content deleted
(→‎{{header|Fortran}}: Added Fortran 77 version (probably it works with earlier Fortran versions as well))
(→‎Recursive: C and C++ versions)
Line 164: Line 164:
ESAC
ESAC
;
;

=={{header|C}}==
=== Iterative ===
<c>
int factorial(int n)
{
int result = 1;
for (int i = 1; i <= n; ++i)
result *= i;
return result;
}
</c>
=== Recursive ===
<c>
int factorial(int n)
{
if (n == 0)
return 1;
else
return n*factorial(n-1);
}
</c>

=={{header|C++}}==
The C versions work unchanged with C++, however, here is another possibility using the STL and boost:
<cpp>
#include <boost/config.hpp>
#include <boost/counting_iterator.hpp>

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


=={{header|Forth}}==
=={{header|Forth}}==