daily pastebin goal
29%
SHARE
TWEET

Untitled

a guest Mar 19th, 2019 60 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. // Note:  the answer for the looping factorial is wrong for integers > 12.  Why?
  3.    
  4.    //This is because of overflow. The int type has only four bytes, or 32 bits, to represent values. The upper limit for an
  5.    //int's value is thus 2^32 = 4,294,967,296, which is less than 13!. Thus, 13! cannot be represented by a standard int
  6.    
  7. //What happens if we change fact from an int to a long?  to a float?  to a double?
  8.  
  9.    //int -> long int: the variable now has eight bytes, or 64 bits. 2^64 ~ 1.884E19. This is apt till 21!, which ~ 5.109E19.
  10.    //int -> float: the function is only accurate for n<14. This is an improvement but not by much.
  11.    //int -> double: the function is accurate for n<23.
  12.  
  13. //If you use a float or a double, when is the answer not exactly correct?
  14.  
  15.    //The answer will not be exactly correct when approaching the digit limit for each type. The "maximum value" for a floating-point
  16.    //is slightly different than that of an int, because the memory of a float/double also depend on decimal place.
  17.  
  18. #include <iostream>
  19. #include <iomanip>
  20. using namespace std;
  21.  
  22. int nFactorial(int nVal);
  23.  
  24. int main(void)
  25. {
  26.    //changes the number of digits shown by cout
  27.    cout.precision(100);
  28.    
  29.     int n = 5;
  30.     int n2;
  31.     int fact;
  32.  
  33.     cout << "enter an integer number: "<<endl;
  34.     cin >> n;
  35.    
  36.    // calculate n factorial with a loop
  37.     n2 = n;
  38.  
  39.    fact = 1;
  40.    while (n2 > 1)
  41.    {
  42.       fact *= n2;
  43.       n2--;
  44.    }
  45.    cout << n << " factorial is: " << fact << endl;
  46.  
  47.    // now uncomment the line below, and do it using your recursive function:
  48.    fact = nFactorial(n);
  49.    cout << n << " recursive factorial is: " << fact << endl;
  50.  
  51.    return 0;
  52. }
  53.  
  54. int nFactorial(int nVal) {
  55.    int factResult;
  56.    
  57.    if (nVal > 1) {factResult = nVal * nFactorial(nVal-1);}
  58.    
  59.    else if (nVal == 0) {factResult = 1;}
  60.    
  61.    else {factResult = 1;}
  62.    
  63.    return factResult;
  64. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top