Tuesday, January 12, 2010

String reverse in Java

In SPOJ, there is a problem to take two integers and reverse them and find their sum and reverse the sum.

The catch here is when two large integers are given. In java there is a object to help you with reverse, for deleting a char at a index in a string and lot more. It is StringBuffer class.

But the solutions to the problems in C takes very less time and space than Java does. I am not sure how thats possible.

Factorial and their trailing zeroes

In SPOJ, there is a problem to find the number of trailing zeroes in the factorial of a number. Though the question seems intimidating, the solution is rather simple.

zeroes come from multiplying the number by 10. To find the number of times the factorial has been multiplied by 10, we can find the number of times 10 is a factor in the factorial expansion of the number. 5 x 2 = 10 is also possible. So instead of finding the factors of 10, we can find it for 5. All the powers of 5 like, 25,125,etc should also be considered to add number of 5 factors to the expansion.

Thus, to find number of trailing zeroes, keep adding the floor of (num/power of 5) until the division is less than 1. The reason why we ignore the reminders in the factors are we need only whole factors not partial ones.

For more detailed explanation see the Source

Monday, January 11, 2010

BitInteger Java solution for finding factorial

In SPOJ, there is a problem to find factorial for numbers between 1 and 100. Though the algorithm for the problem is very easy and simple, finding the right datatype to handle the factorial of larger numbers was not so easy. But the solution is however made simple by java.math.Integer

Amazing thing about BigInteger, the number of digits that it can hold is limited by the memory of the system. It would be unfair to the rest of people who are trying to find the solution if I post the solution here but I can sure help others and save the time I spent researching on this problem.

Follow this sample program: http://leepoint.net/notes-java/data/numbers/60factorial.html