Advertisement
svetlai

TrailingZeroesInNFactorial

Jan 16th, 2015
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.36 KB | None | 0 0
  1. namespace TrailingZeroesInNFactorial
  2. {
  3.     using System;
  4.  
  5.     /// <summary>
  6.     /// Problem 18.* Trailing Zeroes in N!
  7.     /// Write a program that calculates with how many zeroes the factorial of a given number n has at its end.
  8.     /// Your program should work well for very big numbers, e.g. n=100000.
  9.     /// Examples:
  10.     /// n   trailing zeroes of n!   explaination
  11.     /// 10      2                   3628800
  12.     /// 20      4                   2432902008176640000
  13.     /// 100000  24999               think why
  14.     /// </summary>
  15.     public class TrailingZeroesInNFactorial
  16.     {
  17.         public static void Main()
  18.         {
  19.             Console.Write("Please enter an integer number n: ");
  20.  
  21.             int n;
  22.             if (!int.TryParse(Console.ReadLine(), out n))
  23.             {
  24.                 Console.WriteLine("Input was not in the correct format.");
  25.                 return;
  26.             }
  27.  
  28.             Console.Write("{0}! --> ", n);
  29.  
  30.             // fast way - find the number of factors 5 in n! and since there are at least as much factors 2, this equivalents to the number of factors 10, each of which gives one more zero
  31.             int zerosCount = 0;
  32.             while (n > 0)
  33.             {
  34.                 n = n / 5;
  35.                 zerosCount += n;
  36.             }
  37.  
  38.             Console.WriteLine("trailing zeroes : {0}", zerosCount);
  39.         }
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement