Reputation: 437
My code does factorials for numbers, but for some reason whenever i input a number 13 or higher, it either give a wrong number or somehow gets a negative number. Any suggestions?
List<int> myList = new List<int>();
Console.WriteLine("My Job is to take the factorial of the number you give");
Console.WriteLine("What is the number?");
string A = Console.ReadLine();
int C = Convert.ToInt32(A);
int k = C;
int B = C;
int U = C - 1;
Console.Write("{0} ", B);
while (U != 0)
{
k *= U;
Console.Write("* {0} ", U);
U--;
}
Console.WriteLine(" = {0}", k);
Console.ReadLine();
Upvotes: 0
Views: 2653
Reputation: 13179
An integer is 32-bit, so max value is 2,147,483,647. 13! equates to a larger value: 6,227,020,800. You'll have to change to long
to go any higher than 12!, which as a 64-bit number, would give you up to 9,223,372,036,854,775,807.
Type Max Fact Max Value
int 12! 6,227,020,800
long 20! 9,223,372,036,854,775,807
ulong 20! 18,446,744,073,709,551,615
Changing to long at least lets you go to 20! You'd have to change to a floating point to go beyond that in most systems, and even then, you'll start seeing rounding errors. Not even an unsigned long lets you get to 21!
Now, to get beyond 20!, you can use the BigInteger structure (great code project examples are out there). It has no defined upper or lower bounds, but you can run into memory/system issues if the numbers are too large for your system. According to MSDN:
The BigInteger type is an immutable type that represents an arbitrarily large integer whose value in theory has no upper or lower bounds.
int factorial = 25;
BigInteger bigInt = 1;
while (factorial > 1)
bigInt = BigInteger.Multiply(factorial--, bigInt);
var output = bigInt.ToString(); // Would give you the 26 digits
Resources:
Upvotes: 5
Reputation: 4833
You are getting integer overflow https://en.wikipedia.org/wiki/Integer_overflow You can use
long k = C;
instead of
int k = C;
to increase overflow limit to 2^63 - 1 instead of 2^31 - 1
Upvotes: 0
Reputation: 13765
You're working with integers
, which have a maximum value of 2,147,483,647
(13 numbers)
You need to work with a larger numeric type like say int64
, long
, or other in order to solve your immediate problem.
Upvotes: 0