Simple Factorial Program

Page 1 of 1

3 Replies - 10710 Views - Last Post: 22 October 2008 - 06:33 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=68669&amp;s=fc214e48233de423021a353f362d618a&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

#1 seuzy13

Reputation: 1
• Posts: 17
• Joined: 18-July 08

Simple Factorial Program

Posted 22 October 2008 - 06:04 PM

I have written a very simple factorial program, and it works well up until the number thirteen. At that point, the results become inaccurate. I am wondering why. It doesn't appear to be a wrap-around problem, because it hadn't even started using scientific notation (or whatever you want to call it) with 12!. I understand these numbers are large, and I may have reached the limit of memory, but I'm not exactly sure how, because I thought numbers wrapped around when that happened, and I would wind up with a very large negative number.

Anyone care to explain for curiosity's sake why this is the case? Thanks a bunch.

```
//A program which inputs an integer value, checks that it is positive, and
//outputs its factorial, using the formulas:
//	factorial(0) = 1
//	factorial(n) = n * factorial(n-1)
//Author- SB
//Date- 10/22/08

#include <iostream>

using namespace std;

int main (void) {
double n; //user-inputted number to take factorial of
int factorial; //keeps the running factorial
cout << "Enter a positive integer: ";
cin >> n;

if ( n >= 0 ) {
for (int i = 0; i <= n; i++) {
if (i == 0)
factorial = 1;
else
factorial = factorial * i;
}

cout << "The factorial of " << n << " is " << factorial << endl;
} else {
cout << "That is not a positive integer\n";
}
}
```

Is This A Good Question/Topic? 1

Replies To: Simple Factorial Program

#2 brds

Reputation: 76
• Posts: 515
• Joined: 22-October 08

Re: Simple Factorial Program

Posted 22 October 2008 - 06:26 PM

It is an overflow:
2^31=2,147,483,648 /* int = 32 bits, 31 for the number, 1 for sign */

13!=6,227,020,800

```int n; //user-inputted number to take factorial of
double factorial; //keeps the running factorial
```

will work better than:
```double n; //user-inputted number to take factorial of
int factorial; //keeps the running factorial
```

#3 seuzy13

Reputation: 1
• Posts: 17
• Joined: 18-July 08

Re: Simple Factorial Program

Posted 22 October 2008 - 06:30 PM

Ah. That was an oversight on my part. Obviously, I did mean to make the factorial variable a double and the variable "n" an integer. Okay, and I do see now that it is over the limit for long integer. Thanks. As obvious as that was, I could have looked at the code all day and never seen it.

#4 brds

Reputation: 76
• Posts: 515
• Joined: 22-October 08

Re: Simple Factorial Program

Posted 22 October 2008 - 06:33 PM

Sometimes all you need is a second set of eyes