Jump to content

While Loop Issues


AJinNYC
Go to solution Solved by AJinNYC,

Recommended Posts

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. 

Link to comment
Share on other sites

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 by AJinNYC
Link to comment
Share on other sites

  • Solution
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);
?>
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.