• Log in or sign up for an account here: https://www.sythe.org/login

Factorials

Red Fuel Tank

Member
Joined
Jan 5, 2009
Sythe Gold
0
Messages
87
Location
New York CITY, Yoosah
Factorials
I can't help but feel that there's a simpler way to do factorials in c++

You can really only input 0-5 for f.

here's my code:


Code:
#include <iostream>
#include <string>

using namespace std;

int main(){
	cout.setf( ios_base::boolalpha );
	char end = 'e';
	int f = 0;

	cout << "Enter a positive integer to computer the factorial of: ";
	cin >> f;

	int p = f, e = f;
	int q, w, r, t, y = 0;
	bool done = false;
	
	while (!done){
		for (;f >= 0; --f){
			switch (f){
				case 0:
					done = true;
					break;
				case 1:
					done = true;
					break;
				case 2:
					t = f - 1;
					e = e * t;
					break;
				case 3:
					w = f - 1;
					e = e * w;
					break;
				case 4:
					q = f - 1;
					e = e * q;
					break;
				case 5:
					y = f - 1;
					e = e * y;
					break;
			}
		}
	}

	cout << p << "! = " << e;
	cin >> end;
}
 
Factorials
Code:
int fact(int n)
{
	int i, retval = 1;
	if(n<=1)
		return 1;
	for(i = n; i; i--)
	{
		retval *= i;
	}
	return retval;
}

Can be done through recursion as well.
 
Factorials
Code:
int fact(int n)
{
	int i, retval = 1;
	if(n<=1)
		return 1;
	for(i = n; i; i--)
	{
		retval *= i;
	}
	return retval;
}

Can be done through recursion as well.
doesn't the second i in the for loop need a condition?
 
Factorials
It is a condition; it's false when i = 0.
 
Runescape Gamblingrunescape gambling
Back
Top