A factorial of the number of end zeros

 
 

   // Given a positive integer n, n Calculate the factorial n! The end of the number "0" is contained.

  • 5! = 120, the end of which the number contained in the "0" is 1;
  • 10! = 3628800, which contained the end of the number "0" is 2;
  • 20! = 2432902008176640000, which contained the end of the number "0" is 4.
  • //analysis:
  • The number of mantissa multiplying two numbers 0 is actually dependent on the number of factors 2 and 5
  • Every two consecutive numbers will have a factor of 2
  • Only you need to be concerned about the number of factor 5
  • n = 5*K + r(0<= r <= 4)
  • n! = (5*K) * (5*(K-1)) * (5*(K-2)) * ... * 5 * A
  • f (n!) = g (n!) = g (5 ^ K * K! * A) = K + g (K!) = K + f (K!), where K = n / 5 (rounded) .
  • 0 <= n <= 4时,f(n!)=0
    • f(5!) = 1 + f(1!) = 1
    • f(10!) = 2 + f(2!) = 2
    • f(20!) = 4 + f(4!) = 4
    • f(100!) = 20 + f(20!) = 20 + 4 + f(4!) = 24
    • f(1000!) = 200 + f(200!) = 200 + 40 + f(40!) = 240 + 8 + f(8!) = 248 + 1 + f(1) =249













. 1
#include <the iostream> 2 the using namespace STD; . 3 . 4 int GetN_1 ( int n-) . 5 { . 6 IF (n-< . 5 ) . 7 { . 8 return 0 ; . 9 } 10 the else . 11 { 12 is return (n-/ . 5 + GetN_1 (n- / 5 )); // recursive factorial find a number of zeros at the end 13 is } 14 } 15 int GetN_2 ( int n-) //Cyclic manner to find a factorial of the number of end zeros 16 { . 17 int m, COUNT = 0 ; 18 is for ( int I = . 1 ; I <= n-; I ++ ) . 19 { 20 is m = I; 21 is the while (m% . 5 == 0 ) 22 is { 23 is COUNT ++ ; 24 m / = . 5 ; 25 } 26 is 27 } 28 return COUNT; 29 } 30 int main () 31 is { 32 cout << GetN_1(1000) << endl; 33 cout << GetN_2(1000) << endl; 34 35 return 0; 36 }

 

Guess you like

Origin www.cnblogs.com/delongzhang/p/11027442.html