In the written test, I think many people will encounter factorial programming questions. Today, I suddenly remembered my first written test. I encountered such a question, but I haven't typed it on my computer. I just want to write it. I don't know if everyone has done the right thing during the written test?
Many people may use int, double, and Other types to store results. However, this can easily cause overflow. If you don't believe it, try the 100 factorial! In fact, if I used Perl and then wrote it in the bigint type, it would be unnecessary. In addition, Erlang also seems to have a factorial module that can be directly written. Aside from this, we need to consider overflow when using strong types of languages such as Java, C #, and so on. Code . However, I just obtained a 12345 factorial and found that the speed was slow. I hope you can advise me if there is any higher efficiency. Algorithm . Code
Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. text;
Namespace Leleapplication3
{
Class Program
{
Static Void Main ( String [] ARGs)
{
Console. writeline ( " Enter the number you want to calculate: " );
Long N = Convert. toint64 (console. Readline ());
Console. Write ( " The factorial of {0} is: " , N );
Console. writeline (getresult (n ));
}
Static String Getresult ( Long N)
{
List < Long > Listresult = New List < Long > ();
Listresult. Add ( 1 );
Int Poscount = 1 ; // Total number of records
For ( Long I = 1 ; I <= N; I ++ )
{
Long Carry = 0 ;
For ( Int J = 0 ; J < Poscount; j ++ )
{
// Multiply first
Listresult [J] * = I;
// Add carry
Listresult [J] + = Carry;
Long Temp = Listresult [J];
// Storage single digit
Listresult [J] % = 10 ;
Carry = Temp / 10 ;
If (Carry > 0 && J = Listresult. Count - 1 )
{
Poscount ++ ;
Listresult. Add ( 0 );
}
}
}
Stringbuilder sb = New Stringbuilder ();
For ( Int I = Listresult. Count - 1 ; I > = 0 ; I -- )
{
SB. append (listresult [I]. tostring ());
}
Return SB. tostring ();
}
}
}