Today i saw a problem which was asked often in technical round of good companies.
Problem : Finding the first non zero digit in the factorial of a number ( for 5! = 120 first non zero digit is 2 ).
Solution : If number is such that its factorial is within the range of even long long then we can use any brute force method like removing digit one by one till we don't get first non zero digit ( though it wont be efficient ).
Here is better solution , i am not claiming it is best , if any one know better please comment it.
We can easily calculate number of zero in the factorial of a number by dividing the number first by 5 then 5 ^ 2 then 5 ^ 3 .......and adding result till 5^i < number.
Let we get that number has n number of zero then we are sure that the number has at least n number of 2 and n number of 5. What we have to do is to just remove n number of 2 and 5 from given number and keep track of last digit , till we get the answer.
here is the working code
int main ()
{
int Num2, Num5;
int Ldigit = 1, tmp;
int Num, NumZero = 0, i;
scanf ( " %d", &Num );
for ( i = 1; ;i++ )
{
tmp = pow ( 5, i );
if ( tmp > Num )
break;
NumZero += Num / tmp;
}
Num2 = Num5 = NumZero;
for ( i = 2; i <= Num; i++ )
{
tmp = i;
while ( !(tmp % 2) && (Num2>0) )
{
tmp /= 2;
Num2--;
}
while ( !(tmp % 5) && (Num5>0) )
{
tmp /= 5;
Num5--;
}
Ldigit *= tmp;
Ldigit %= 10;
}
printf ( " Last Digt = %d\n", Ldigit );
return 0;
}
Saturday, September 6, 2008
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment