Code Chef "Yet Another Number Game" Problem Solved With PHP (Code: NUMGAME)
I love spending time on solving coding problems rather than watching tv or playing video games dunno why, but I love it, just an hour ago I started reading this problem here. And had developed a solution to the said problem:<?php
$ip = fopen('php://stdin', "r");
$op = fopen('php://stdout',"w");
$test_cases = trim(fgets($ip));
$c = 0;
while($c < $test_cases){
$turn = 1;
$case = trim(fgets($ip));
while($case>2){
$limit = $case/2;
$a=2;
while(($a < $limit)){
$factor = $case/$a;
if(floor($factor) == $factor){
break;
}else{
$factor = 1;
}
$a++;
}
$case = $case - $factor;
$turn++;
}
while($case>1){
$case--;
$turn++;
}
if(($turn % 2) == 0){
fwrite($op, sprintf("%s\n","ALICE"));
}else{
fwrite($op, sprintf("%s\n","BOB"));
}
$c++;
}
?>
I was amazed because while testing on the IDE here, and it was working all so fine, but when I submitted the solution to the codechef bot, it just gave me a time limit exceeded error. My jaws dropped when the error continued even after I had optimized the code pretty well. But as the say, you miss out things just right in front of you, thats it, I missed out an important pattern, the script was generating just even and odd outputs, in a formula not much known, study the test cases 1-10 and you will just say... AH-HA!...
So the solution simply becomes:<?php
$ip = fopen('php://stdin', "r");
$op = fopen('php://stdout',"w");
$test_cases = trim(fgets($ip));
$c = 0;
while($c < $test_cases){
$turn = 1;
$case = trim(fgets($ip));
if(($case % 2) == 0){
fwrite($op, sprintf("%s\n","ALICE"));
}else{
fwrite($op, sprintf("%s\n","BOB"));
}
$c++;
}
?>
Easy Simple Slick!
Happy to solve it!
I see not many developers use PHP to get things done at CodeChef, maybe my findings helps others
Cheers!