I have a problem with a code attempting to do a factorial of a number. For numbers 12 and below, the code works fine, but when I do 13 and above it outputs the wrong number.

#include <iostream>
using namespace std;

int number;
int number2;

int main()
{
cout << "Enter a number to do a factorial of:\t";
cin >> number;
number2=number;
do
{
    number=number-1;
    number2=number2*number;
   
}while(number>1);
cout << "Your number is: ";
cout << number2;
cout << endl;
system("pause");
cout << endl;
}

Thanks in advance.

What kind of factorial is this? An input of 3 will result in an output of 6... it should be 3 * 1. If you enter 4 you will get something like 24. Factorials break numbers down like this: 12 factorial = 2 * 2 * 3. To implement a factorial that way you could start by doing mod 2, print out 2 if % 2 = 0, else add one and try mod 3 etc.

Note: that is a bad way to try to factorize but it will work

What kind of factorial is this? An input of 3 will result in an output of 6... it should be 3 * 1. If you enter 4 you will get something like 24. Factorials break numbers down like this: 12 factorial = 2 * 2 * 3. To implement a factorial that way you could start by doing mod 2, print out 2 if % 2 = 0, else add one and try mod 3 etc.
Note: that is a bad way to try to factorize but it will work

He's doing factorial, not factorization. Bigggg difference.

Zothos - the problem is that above 12! an int cannot hold the value created. You gain a little bit if you change it to unsigned int (now you can store 4billion and change compared to 2billion+ of a signed int) You could change your number type to double, then you're good up to about 20! . If your compiler supports it, and most (all?) current ones do in some form is use a long long int, which is a 64bit value, which can hold a darn big number.

Ah yes I see! That would explain my confusion. Sorry i missed it!

On looking at it again, I had it backwards. unsigned long long int overflows at 20!, not doubles. Type double can keep on going and going quite a ways.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.