My factorial just works until 31

My calculatorĀ“s factorial works ok but when you use numbers higher than 31 the result will be a negative number or zero and I donĀ“t know why. May someone explain it to me? Here is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
//Calculator by Enrique Junchaya
#include <iostream>

using namespace std;

double addition(double x, double y)
{
	return x+y;
}

double substraction(double x, double y)
{
	return x-y;
}

double multiplication(double x, double y)
{
	return x*y;
}

double division(double x, double y)
{
	return x/y;
}

int factorial(int x)
{
	int n, m=1;
	for ( n=x ; n>0 ; --n )
	{
	 	m *= n;
	}
	return m;
}

int main()
{
	char o;
	
	double a, b;
	int c;
	label:
	cout << "What operation do you want to do?" << endl;
	cout << "Write +, -, *, / or !." << endl;
	cin >> o;
	switch(o)
	{
		case '+':
			cout << "Now write the numbers." <<endl;
			cin >> a;
			cout << "+" << endl;
			cin >> b;
			cout << "_______" <<endl;
			cout << addition(a, b) << endl;
			goto label;

		case '-':
			cout << "Now write the numbers." << endl;
			cin >> a;
			cout << "-" << endl;
			cin >> b;
			cout << "_______" << endl;
			cout << substraction(a, b) << endl;
			goto label;

		case '*':
			cout << "Now write the numbers." << endl;
			cin >> a;
			cout << "*" << endl;
			cin >> b;
			cout << "_______" <<endl;
			cout << multiplication(a, b) << endl;
			goto label;

		case '/' :
			cout << "Now write the numbers." << endl;
			cin >> a;
			cout << "/" << endl;
			cin >> b;
			cout << "_______" << endl;
			cout << division(a, b) << endl;
			goto label;
			
		case '!':
			cout << "Now write the entire number." << endl;
			cin >> c;
			cout << c << "! = " << factorial(c) << endl;
			goto label;
			
		default:
			cout << "Unknown Character. Try again." << endl;
			goto label;
	}
}
Everything after 12! will give you an incorrect result if ints on your platform are 32 bits long. An integer just can't hold numbers of the size you desire.
And what should I use for bigger numbers?
Either use a double, which can hold up to 10^300 or something, but loses precision, or find a Bignum / multiprecision library to store your numbers (I like the Boost ones).
You can also use an unsigned long long which will let you do factorials from [0,20].
Last edited on
But how I use them I dont know
Same way you use integer. Int, long, long long are all integer types. Unsigned means that the first bit isn't used as a sign bit which means you can have twice as large of a number.
ok I supposed I should use long long
Topic archived. No new replies allowed.