AJinNYC Posted April 14, 2015 Share Posted April 14, 2015 I'm having a bit of problems with the following: <?php function find($initial, $goal){ $looped=0; $string=null; $hold=$goal; while($hold >= $initial){ if(sqrt($hold) % 1 == 0){ $hold=sqrt($hold); $string.=' square '; } else{ $hold=$hold-1; $string.=' increment '; } $looped=$looped++; } return $looped.':'.$string; } echo find(1,100); ?> This should be printing out 5: square increment square increment increment (The part of the string after the colon will ultimately be flipped around, just haven't done that yet). But I'm just getting a never ending loop that ultimately leads to a memory crash of PHP. Quote Link to comment Share on other sites More sharing options...
AJinNYC Posted April 14, 2015 Author Share Posted April 14, 2015 (edited) Just realized this: $looped=$looped++; Should be this: $looped++; And I should get rid of the equals sign in the while loop. However, it's still not returning what I'm expecting. This is the current result: 55: square square square square square square square square square square square square square square square square square square square square square square square square square square square square square square square square square square square square square square square square square square square square square square square square square square square square square square square Edited April 14, 2015 by AJinNYC Quote Link to comment Share on other sites More sharing options...
requinix Posted April 15, 2015 Share Posted April 15, 2015 (edited) if(sqrt($hold) % 1 == 0){It's not safe to use modulus with non-integer numbers. Try something more like if(floor(sqrt($hold)) == ceil(sqrt($hold))){[edit] But you have another problem: sqrt(1) == 1. Edited April 15, 2015 by requinix Quote Link to comment Share on other sites More sharing options...
Solution AJinNYC Posted April 15, 2015 Author Solution Share Posted April 15, 2015 if(sqrt($hold) % 1 == 0){It's not safe to use modulus with non-integer numbers. Try something more like if(floor(sqrt($hold)) == ceil(sqrt($hold))){[edit] But you have another problem: sqrt(1) == 1. That definitely helped. This seems to work: <?php function find($initial, $goal){ $looped=0; $string=null; $hold=$goal; if($initial==0 || $goal==0){ return false; } while($hold > $initial){ $sqrt=sqrt($hold); if(floor($sqrt) == ceil($sqrt)){ $hold=sqrt($hold); $string.=' square '; if($sqrt==1) break; } else{ $hold=$hold-1; $string.=' increment '; } $looped++; } return $looped.':'.$string; } echo find(1,100); ?> Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.