Aaronv
Aaronv

Reputation: 63

recursive vs iterative factorial in C++

I made a shitty c++ programme to calculate the factorial of an entered value wherein I wrote two functions to do the actual calculations independently (one iterative, the other recursive). What doesn't make any sense to me is, why does the iterative factorial collapse at around n = 13 but the recursive goes all the way to the upper boundary of an unsigned long long int?

P.S. I would be grateful to receive any advice whatsoever regarding the quality of my code, and will happily amend it, thaanks.

#include <iostream>
using namespace std;

unsigned long long int rekursiv_fak (int); // function prototyping
unsigned long long int iterativ_fak (int);

int main () {
  unsigned int n; // factorial is defined only for positive integers !!
  cout << "Enter a positive integer value: ";
  cin >> n;
  cout << "The factorial of " << n << " is equal to: " << iterativ_fak(n) << " or alternatively " << rekursiv_fak(n) << endl;
  return 0;
}

unsigned long long int rekursiv_fak (int n) {
  if (n == 1)
    return 1;
  return n * rekursiv_fak(n - 1);
}
unsigned long long int iterativ_fak (int n) {
  for (int i{n - 1}; i > 0; --i) 
    n *= i;
  return n;
}

Upvotes: 2

Views: 392

Answers (1)

AlexM4
AlexM4

Reputation: 523

In iterativ_fak() you multiply variable n which has type int. It is 32 bit type and can only store 12! at max. rekursiv_fak() on the other hand returns unsigned long long type variable and therefore has 64 bit to store result of n * rekursiv_fak(n - 1).

Upvotes: 5

Related Questions