c# - Factorial Calculation Fails When Input Is Higher Than 12 -


my code factorials numbers, reason whenever input number 13 or higher, either give wrong number or somehow gets negative number. suggestions?

        list<int> mylist = new list<int>();         console.writeline("my job take factorial of number give");         console.writeline("what number?");         string = 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(); 

an integer 32-bit, max value 2,147,483,647. 13! equates larger value: 6,227,020,800. you'll have change long go higher 12!, 64-bit number, give 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 long @ least lets go 20! you'd have change floating point go beyond in systems, , then, you'll start seeing rounding errors. not unsigned long lets 21!

now, beyond 20!, can use biginteger structure (great code project examples out there). has no defined upper or lower bounds, can run memory/system issues if numbers large system. according msdn:

the biginteger type immutable type represents arbitrarily large integer 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(); // give 26 digits 

resources:


Comments