Thursday, July 30, 2009

Program to find number of zero's in factorial of a number...

Resently a came accross this problem of finding the number of zero's in factorial of a number....
Well i think the logic is really simple...we have to find out the factors that contributes to 1 or more number of 0's.Whenever there are 1 or more zero's at the end of a number it always results in 0's at the end factorial number also.And the number of 5 also gives same number of 0's as there are many more numbers of the 2's compared to 5's.Similarly one 0 from 25 and two 0's from 50 and and soo on....
Hence we can compute the number of zero's by finding a value though the formula
value = (number/5^1+number/5^2+..............+number/5^n)
where
n = number/5;
Hope the idea is clear....
Now as far as the implementation in java is concerned here i also give the code for implementing it in java...
package com.lara;

import java.util.Arrays;
import java.util.Scanner;

public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number for which you want to find zeros");
System.out.println("Enter the total number of the cases");
int cas = sc.nextInt();
long result[]=new long [cas];
System.out.println("Enter the long elements one by one");
long num[] = new long[cas];
for(int i =0 ;i
{
num[i] = sc.nextLong();
}
for(int i=0; i
{
long n = num[i]/5;
for(int i1=1;i1
{
System.out.println("i1: "+i1);
System.out.println("i; "+ i);
result[i] += (long) (num[i]/Math.pow(5, i1));
}
}
System.out.println("number of the zeros are "+ Arrays.toString(result));
}
}

Well the fact remains that the execution time of this program in java is definitly more than that in C/C++....


No comments:

Post a Comment