Advertisement
Fleshian

Trailing Zeroes in N!(1)

Apr 14th, 2014
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.26 KB | None | 0 0
  1. using System;
  2. /*
  3.     Problem 11. * Trailing Zeroes in N!
  4.     Write a program that calculates with how many zeroes the factorial of a given number n has at its end.
  5.     Your program should work well for very big numbers, e.g. n=100000. Examples:
  6.     n       trailing zeroes of n!   explaination
  7.     10      2                       3628800
  8.     20      4                       2432902008176640000
  9.     100000  24999                   think why
  10.  */
  11. class TrailingZeroesInNFactorial
  12. {
  13.     static void Main()
  14.     {
  15.         // the formula for finding trailing zeros in factorial is:
  16.         // if n > 5  zeroes = n /5
  17.         // if n > 5^2  zeroes = (n / 5^2) + (n / 5)
  18.         // if n > 5^3  zeroes = (n / 5^3 )+ (n / 5^2) + (n / 5)
  19.     // if n > 5^4  zeroes = (n / 5^4 )+ (n / 5^3) +  ....
  20.         Console.Write("n = ");
  21.         int n = int.Parse(Console.ReadLine());
  22.         int zeroCounter = 0;
  23.         int divide;
  24.         int power = 0;
  25.  
  26.         while (true)
  27.         {
  28.             divide = n / (int)Math.Pow(5, power);
  29.             if (divide > 0)
  30.             {
  31.                 zeroCounter += divide;
  32.             }
  33.             else
  34.             {
  35.                 break;
  36.             }
  37.             power++;
  38.         }
  39.         Console.WriteLine(zeroCounter);
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement