Factorial

Can any explain how line 8 works.


// factorial calculator
#include <iostream>
using namespace std;

long factorial (long a)
{
if (a > 1)
{
return (a * factorial (a-1)); // this line..................
}
else
{
return (1);
};
}

int main ()
{
long number;
cout << "Please type a number: ";
cin >> number;
cout << number << "! = " << factorial (number);
cin.ignore(12,'/n');

}
You don't have line 8. Your lines are not counted :D
This is not doing what you want it to do because on the second iteration you will be way off the index you started with:

first iteration: where a = 6, will return factorial(30);
second iteration: where a = 30, will return factorial(870);

Look at this instead:
1
2
3
4
5
6
long factorial(long a, long f = 0) // one variable to index, one for product
{
  if(!f) f = a; // first iteration so set f to a
  f *= (--a); // a * (a-1)
  return (a > 1) ? factorial(a,f) : f; // if we have 1, return product else keep iterating
}
Good explanation ( Texan40 ) thanks for your help.
-------------------------------------------------------------------------------------
i learn pointer several times is that something like this:

int A ;
int * B ;
int **C ;

B = &A ;
*B = 20;
**C = &B;

(B) is pointed to address of (A ) if assign a value to (B) it assign to the address (A) and toked again
and if you assign a value to the (C) its assigned to address of (B)
in case (A) is Equal To (**C).


is this right are i did not understand
Last edited on
You have function factorial that recursively calls itself. So it calculates correctly the factorial.
In fact the line

return (a * factorial (a-1));

looks like

a * ( a -1 ) *...*1

So you get the required value.
It would be a good explanation except it's inaccurate, and there is no reason for a factorial function to take two arguments.

1
2
3
4
5
6
7
8
9
10
11
long factorial (long a)
{
     if (a > 1)
     {
          return (a * factorial (a-1)); // this line..................
     }
     else
     {
           return (1);
     }
} 


Recursion is all about the divide and conquer strategy.

If you call this with a = 6, it will return 6*factorial(5), 5 will return 5*factorial(4) down until you get to 1. the net result is 6*5*4*3*2*1 or the factorial of 6.

However, a factorial function is a very poor candidate for recursion as it is so easily converted into a loop.
Topic archived. No new replies allowed.