// factorial calculator
#include
using namespace std;
long factorial (long a)
{
if (a > 1)
return (a * factorial (a-1));
else
return (1);
}
int main ()
{
long number;
cout << "Please type a number: ";
cin >> number;
cout << number << "! = " << factorial (number);
return 0;
}
That would be how to do factorial recursively. To do it by simply using a for loop you would do:
int factorial(int a) { int f = 1; for(int i=1;i<=a;i++) { f = f * i; } return f; }
so what that does is go through a for loop (starting at 1 and ending when i > a) and multiplies f by i. Then it returns the calculated value. I assume you wanted this for a larger program as such I made it as a function. If you want the entire program to only do factorials, then use the main function that the person above me posted.
Also, I can't remember C++ that well, does int go higher than 255? If it doesn't you probably want to change int to long.
If that didn't really answer your question call me, if you still have my number. If not send me an email.
no subject
Date: 2006-10-18 09:20 pm (UTC)// factorial calculator #include using namespace std; long factorial (long a) { if (a > 1) return (a * factorial (a-1)); else return (1); } int main () { long number; cout << "Please type a number: "; cin >> number; cout << number << "! = " << factorial (number); return 0; }no subject
Date: 2006-10-18 10:30 pm (UTC)int factorial(int a)
{
int f = 1;
for(int i=1;i<=a;i++)
{
f = f * i;
}
return f;
}
so what that does is go through a for loop (starting at 1 and ending when i > a) and multiplies f by i. Then it returns the calculated value. I assume you wanted this for a larger program as such I made it as a function. If you want the entire program to only do factorials, then use the main function that the person above me posted.
Also, I can't remember C++ that well, does int go higher than 255? If it doesn't you probably want to change int to long.
If that didn't really answer your question call me, if you still have my number. If not send me an email.
no subject
Date: 2006-10-19 05:28 am (UTC)For a 16-bit int, it's 32767.
I think you should have much of a problem.
Another way of doing JonAdler's program is
int factorial (int a)
{
for (int i = (a-1); i>1; i--)
{
a = a*i;
}
return 1;
}
But his way is simpler. Mine just forces you to count down to one, rather than up to a.
But mine is obviously bettar, since a > f.
no subject
Date: 2006-10-19 05:29 am (UTC)Meant to add that. -.-