lmarkov

Zeros At The End Of Factorial N

Dec 11th, 2012
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.20 KB | None | 0 0
  1. /*
  2.  * * Write a program that calculates for given N how many trailing zeros present at the end of the number N!. Examples:
  3.     N = 10  N! = 3628800  2
  4.     N = 20  N! = 2432902008176640000  4
  5.     Does your program work for N = 50 000?
  6.     Hint: The trailing zeros in N! are equal to the number of its prime divisors of value 5. Think why!
  7. */
  8.  
  9. using System;
  10. using System.Numerics;
  11.  
  12. class ZerosAtTheEndOfFactorialN
  13. {
  14.     static void Main()
  15.     {
  16.         BigInteger numberN;
  17.         BigInteger trailingZeros = 0;
  18.         BigInteger divider = 5;
  19.         string invalidInput = "Please enter a valid number greater than 0!" + Environment.NewLine;
  20.         Console.WriteLine("Enter a value for N: ");
  21.         while (!(BigInteger.TryParse(Console.ReadLine(), out numberN) && numberN > 0))
  22.         {
  23.             Console.WriteLine(invalidInput);
  24.             Console.WriteLine("Enter a value for N: ");
  25.         }
  26.  
  27.         for (int i = 5; i <= numberN*2; i = i * 5)
  28.         {
  29.             trailingZeros = trailingZeros +  (numberN / i);            
  30.         }
  31.         Console.WriteLine("There are {0} trailing zeros in factorial of number {1}!" + Environment.NewLine, trailingZeros, numberN);
  32.         Main();
  33.     }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment