Question

There is a section of the book I am using to learn c++ which teaches about optimizing functions.

The code is as follows:

#include <iostream>

using namespace std;

int computeFactorials(int, int);

int factorial(int);

int main() {
    computeFactorials(1, 5);
    return 0;
}

int computeFactorials(int num, int max) {
    cout << "Factorial of " << num << ": ";
    cout << factorial(num) << endl;
    num++;
    if(num > max)
        return 0;
    else
        computeFactorials(num, max);
}

int factorial(int n) {
    int result;
    if (n == 1)
         result = 1;
    else
         result = (factorial(n-1) * n);
    return result;
}

Here is the program execution:

Factorial of 10: 3628800

C:\MyPrograms\c++ optimize.cpp -o optimize.exe

C:\MyPrograms>optimize
Factorial of 1: 1
Factorial of 2: 2
Factorial of 3: 6
Factorial of 4: 24
Factorial of 5: 120

I can follow up to num == 3, but when it gets to 4 my logic doesn't add up with the results. I am reading the code like this:

computeFactorials(1,5), 1 meaning the number to start at, and 5 meaning the maximum number of loops. I'm going to start at 3 per se because I understand 1 and 2 as num.

"Factorial of " (3) : factorial(3), then in the factorial function 3 is subtracted by 1 equaling 2, and then multiplied by 3 for a result of 6.

However, when the program gets to num equaling 4 this doesn't seem to make any sense anymore. Because the int result of the factorials() functions should equal 12 not 24.

else result = (factorials (4-1) * 4) ; 

3 * 4 = 12, not 24. How is this program getting to 24 and not 12? Then once again doing the same thing on num = 5, getting 120 rather than 20.

Please help me understand, I am still very nooby in this language, thank you. :)

Was it helpful?

Solution

then in the factorial function 3 is subtracted by 1 equaling 2, and then multiplied by 3 for a result of 6

No.

In the factorial function, 3 "is subtracted by 1" equalling 2, then this 2 is passed to factorial in a recursive call:

  • factorial(2) * 3
  • = factorial(1) * 2 * 3
  • = 1 * 2 * 3
  • = 6

The result of this call is what is multiplied by 3 for a result of 6.

It's (factorial(n-1) * n), not ((n-1) * n).


However, when the program gets to num equaling 4 this doesn't seem to make any sense anymore, because the int result of the factorials() functions should equal 12 not 24.

If factorial(3) is 6, then factorial(4) clearly cannot be only 12 because that's only twice 6. It's not grown enough.

  • factorial(3) * 4
  • = factorial(2) * 3 * 4
  • = factorial(1) * 2 * 3 * 4
  • = 1 * 2 * 3 * 4
  • = 24

3 * 4 = 12, not 24

Correct, but that is not 4 factorial. 4 factorial is 1 * 2 * 3 * 4.

I suspect you're sort of half-confusing factorial with the fibonacci sequence.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top