Gngogh
Gngogh

Reputation: 177

PHP nested loop Bug

i have developed the following code to find out all armstrong numbers between 100 and 1000, but for some reason is not behaving as expected.

for($i=99;$i<1000;$i++){
    $x = str_split($i);
    $arm = 0;
    foreach ($x as $n){
        $arm = $arm + pow($n,3);
        if ($arm == $i){
            echo $i."\n";
        }
     }
 }

The code checks the value of $i against the value of $arm, if it match, it prints $i. Meaning that $i is a armstrong number. the output is the following.

153
370
370
371
407

For some reason is printing twice 370, but according to the first loop $i will hold only once the value of 370. So why im i getting twice 370???

Thanks in advance for any help.

Upvotes: 1

Views: 106

Answers (1)

Maarten van Middelaar
Maarten van Middelaar

Reputation: 1721

You get 370 twice because:

33 + 73 == 33 + 73 + 03  //27 + 343  == 27 + 343 + 0

Try to put the if statement after the foreach loop when you have added everything together:

for($i = 99; $i < 1000; $i++){

    $x = str_split($i);
    $arm = 0;

    foreach ($x as $n){
        $arm = $arm + pow($n, 3);
    }

    if ($arm == $i){
        echo $i . "\n";
    }

}

Upvotes: 2

Related Questions