Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Note: the answer for the looping factorial is wrong for integers > 12. Why?
- //This is because of overflow. The int type has only four bytes, or 32 bits, to represent values. The upper limit for an
- //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
- //What happens if we change fact from an int to a long? to a float? to a double?
- //int -> long int: the variable now has eight bytes, or 64 bits. 2^64 ~ 1.884E19. This is apt till 21!, which ~ 5.109E19.
- //int -> float: the function is only accurate for n<14. This is an improvement but not by much.
- //int -> double: the function is accurate for n<23.
- //If you use a float or a double, when is the answer not exactly correct?
- //The answer will not be exactly correct when approaching the digit limit for each type. The "maximum value" for a floating-point
- //is slightly different than that of an int, because the memory of a float/double also depend on decimal place.
- #include <iostream>
- #include <iomanip>
- using namespace std;
- int nFactorial(int nVal);
- int main(void)
- {
- //changes the number of digits shown by cout
- cout.precision(100);
- int n = 5;
- int n2;
- int fact;
- cout << "enter an integer number: "<<endl;
- cin >> n;
- // calculate n factorial with a loop
- n2 = n;
- fact = 1;
- while (n2 > 1)
- {
- fact *= n2;
- n2--;
- }
- cout << n << " factorial is: " << fact << endl;
- // now uncomment the line below, and do it using your recursive function:
- fact = nFactorial(n);
- cout << n << " recursive factorial is: " << fact << endl;
- return 0;
- }
- int nFactorial(int nVal) {
- int factResult;
- if (nVal > 1) {factResult = nVal * nFactorial(nVal-1);}
- else if (nVal == 0) {factResult = 1;}
- else {factResult = 1;}
- return factResult;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement