Skip to content

Instantly share code, notes, and snippets.

@taisyo7333
Last active October 22, 2016 11:46
Show Gist options
  • Save taisyo7333/6a646e2119605c1e4865eb969feb16e6 to your computer and use it in GitHub Desktop.
Save taisyo7333/6a646e2119605c1e4865eb969feb16e6 to your computer and use it in GitHub Desktop.
C++ Factorial loop recursion
#include<iostream>
int RecursiveFactorial(int number)
{
if (number < 0) throw std::invalid_argument("Negative number is not allowed.");
if (number == 0) return 1;
return number * RecursiveFactorial(number - 1);
}
int LoopedFactorial(int number)
{
if (number < 0) throw std::invalid_argument("Negative number is not allowed.");
int total = 1;
for (int n = number; n >= 0; n--)
{
if (n == 0) total *= 1;
else total *= n;
}
return total;
}
int main()
{
for (int i = 0; i < 5; i++)
{
std::cout << i << "! = " << LoopedFactorial(i) << " , " << RecursiveFactorial(i) << std::endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment