Hello,
I'm trying to calculate factorials with my program, but it is only working for the first few numbers. It compiles fine, so I can't find the problem. Help please! Keep it simple, I am very new to C++ and programming in general.
Here is my code:

#include <iostream>
#include <cmath>
using namespace std;
int factorial(int);
int factorial(int n)
{
        int i=0, fact=1;
        if(n<=1)
        {
                return(1);
        }
        else
        {
            for (i=1; i<=n; i++)
            {
                fact=fact*i;
            } 
        return(fact);
        }
}
int main()
{
    int i, z, q;
    int n=10;
    for (i=0; i<=n; i++)
    {
    q=((2*i)+1);
    z=factorial(q);
    cout<<z <<endl;
    }
system("PAUSE");
return 0;
}    

It works for i=0 to i=6, but after that the values are incorrect.

Let's say i is 6. You're trying to take the factorial of (2 * 6 + 1), or 13. 13! is 6227020800, which overflows even an unsigned 32-bit integer (your range is roughly halved from that by using a signed type). It's not unexpected that you'll start getting funky values very quickly given the rapid growth of factorials.

Edited 4 Years Ago by deceptikon

What's q=((2*i)+1); supposed to be doing?
If you wan tthe factorial of 7, why are you passing 15 to the function? Won't that give you 15! ?

Oh! I changed it to long double, because that's the most memory right? Still not big enough however. I don't know how to approach it other than that. Thank you so much though!

double is usually used for floating point variables (i.e. - they require decimal points).
The results of a factorial calculation are positive integers, so you were fine leaving it as int. To extend the range, you could use unsigned int.

Like "WaltP asked: what is the point of the variable q?

When you say it works from i = 0 to 6, do mean the values are correct? Have you confirmed that?

The results of a factorial calculation are positive integers, so you were fine leaving it as int. To extend the range, you could use unsigned int.

If your value is larger than an int can hold, how is it fine leaving it as an int? Isn't the double giving you the ability to have a larger value -- beyond the capabilities of int -- albiet as an approximation due to magnitude?

This article has been dead for over six months. Start a new discussion instead.