Factorial function

I was at school when i started thinking of making a factorial calc. I arrived home and after some errors i got this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;
int Factorial (int a)
{
	int result;
	result = a;
	int b=a;
	for (a=1;a!=b;a++)
	{
		result = result * (b-a);
	}
	return result;
}
int main()
{
	int value = 5;
	cout << Factorial(value);
	cin.get();
	return 0;
}

and it works, I was really surprised, but what i want to know is if there is any function easier or this is the simplest one.
It seems slightly over-complicated.
Though well done for getting it to work unaided.

1
2
3
4
5
6
7
8
9
int Factorial (int a)
{
    int result = 1;
	
    while (a > 1)
        result *= a--;
		
    return result;
}


I should also add that this function is often used to demonstrate recursion, that is a function which calls itself:
1
2
3
4
5
6
7
int Factorial(int n) 
{
    if (n == 0)                     // Simple case: 0! = 1 
        return 1;           
        
    return (n * Factorial(n - 1));  // General function: n! = n * (n - 1)!
}
Last edited on
The second function would work well? it seems that will only do n*(n-1), if you know what i mean.
Not, for example: 5*4*3*2*1
Last edited on
It only does n * Factorial(n-1), which just so happens to be the same as n!

Factorial(n) =
n * Factorial(n-1) =
n * (n-1) * Factorial(n-2) = ...

Breaking down the problem into smaller pieces, that's what recursion is all about.
Last edited on
Topic archived. No new replies allowed.