Adblock breaks this site

Factorials

Discussion in 'Programming General' started by Red Fuel Tank, Nov 5, 2010.

  1. Red Fuel Tank

    Red Fuel Tank Member

    Joined:
    Jan 5, 2009
    Posts:
    87
    Referrals:
    0
    Sythe Gold:
    0
    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;
    }
     
  2. Govind

    Govind The One Musketeer
    Mudkips Highly Respected Retired Administrator

    Joined:
    Apr 22, 2005
    Posts:
    7,825
    Referrals:
    13
    Sythe Gold:
    23
    Prove it! Trole Tier 1 Prizebox Tortoise Penis Le Monkey UWotM8? Wait, do you not have an Archer rank? Potamus
    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.
     
  3. confuego116

    confuego116 Forum Addict
    Banned

    Joined:
    Oct 9, 2009
    Posts:
    467
    Referrals:
    0
    Sythe Gold:
    0
    Factorials

    doesn't the second i in the for loop need a condition?
     
  4. Govind

    Govind The One Musketeer
    Mudkips Highly Respected Retired Administrator

    Joined:
    Apr 22, 2005
    Posts:
    7,825
    Referrals:
    13
    Sythe Gold:
    23
    Prove it! Trole Tier 1 Prizebox Tortoise Penis Le Monkey UWotM8? Wait, do you not have an Archer rank? Potamus
    Factorials

    It is a condition; it's false when i = 0.
     
< Could not find main class: Gui. Program will exit. | Find Runescape Window >


 
 
Adblock breaks this site