Code Chef FACTORIAL Problem Solved With PHP

Nishant Arora 23/Nov/2011
Facebook
Twitter
LinkedIn
Reddit

Problem Statement Here

This I consider was the easiest problem, if and only if you know the trick to the solution. I found this amazing explanation to share with you guys, I had an idea before I read this, but this made it simpler, I cannot copy the content as the blog is copyrighted. The solution of the problem is given at the end of the article which states:

you can get the same result, if you keep track as you go, by just dividing repeatedly in your calculator by 5's: 4617 ÷ 5 = 923.4 (write down 923), 923.4 ÷ 5 = 184.68 (write down 184), 184.68 ÷ 5 = 36.936 (write down 36), 36.936 ÷ 5 = 7.3827 (write down 7), 7.3827 ÷ 5 = 1.47744 (write down 1), and 1.47744 ÷ 5 is going to be less than 1, so you're done

Once you are through with the algo, implementation is even simpler:

 

<?php
$ip = fopen('php://stdin', "r");
$op = fopen('php://stdout',"w");

$test_cases = trim(fgets($ip));
$c = 0;

while($c < $test_cases){
        $val = trim(fgets($ip));
        $ans = 0;
        $divisor = 5;

        while($val>=5){
                $val = floor($val/$divisor);
                $ans = $ans + $val;
        }
        fwrite($op, sprintf("%d\n", $ans));
        $c++;
}
?>

Working Code Here

Cheers!

Keywords: