Factorial issues Title Description Perhaps you already know the meaning of factorial, n factorial is multiplied by 1 to N, such as:
12! = 1 x 2 x 3 x 4 x 5 x 6 x 7 x 8 x 9 x Ten x x 12 = 479,001,600
The rightmost non-0 bit of the factorial of 12 is 6.
Write a program that calculates the rightmost non-0-bit value of the N (1<=n<=50,000,000) factorial.
NOTE: 10,000,000! There are 2,499,999 zeros.
Enter only one row containing a positive integer n. Output
A single line contains an integer representing the rightmost non-0-bit value.
Sample input
12
Sample output
6
The traditional method of violence will definitely time out, but don't try. Sure enough, the tle.
So the improvement, the end of the 0 minus will certainly not affect the result of it.
Method One, find out N! The number of 5 is removed and the same number of 2 goes out.
As expected, the result was almost timed out.
#include <iostream>#include<cstdio>using namespacestd;intGetfactornumber (unsigned number, unsigned Factor) {intresult =0; if(Factor <2|| Number <1) return-1; while(Number >=Factor) Result+ = number/=Factor; returnresult;}intgetlastdigit (unsigned number) {intresult =1; inti; inttmp; intCount =0; intTotalfactors = Getfactornumber (number,5); for(i = number; I >=1; i--) {tmp=i; while(tmp%2==0&& Count <totalfactors) {tmp/=2; Count++; } while(tmp%5==0) TMP/=5; TMP%=Ten; Result*=tmp; Result%=Ten; } returnresult;}intMain () {intN; scanf ("%d", &N); printf ("%d\n", Getlastdigit (n)); return 0;}
View Code
Method Two, the method of number theory proof, can consult the document
Specific can be self-proof, the time complexity of the modification method (LG (N))
#include <iostream>#include<cstdio>using namespacestd;intGetfactornumber (unsigned number, unsigned Factor) {intresult =0; if(Factor <2|| Number <1) return-1; while(Number >=Factor) Result+ = number/=Factor; returnresult;}intgetlastdigit (unsigned number) {intresult =1; inti; inttmp; intCount =0; intTotalfactors = Getfactornumber (number,5); for(i = number; I >=1; i--) {tmp=i; while(tmp%2==0&& Count <totalfactors) {tmp/=2; Count++; } while(tmp%5==0) TMP/=5; TMP%=Ten; Result*=tmp; Result%=Ten; } returnresult;}intMain () {intN; scanf ("%d", &N); printf ("%d\n", Getlastdigit (n)); return 0;}
View Code
2016-08-11
The rightmost non-0-bit value of the factorial