1

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.

2
  • 1
    Because at 370 you do: 3^3 + 7^3 which already is equal to 370 and you print the number out in your foreach loop. But adding 0^3 to 370 in the next and last iteration still is equal to 370 and you output the number again. Commented Jan 25, 2017 at 22:51
  • Yep. Basically you need to move the if to after the inner loop. Commented Jan 25, 2017 at 22:52

1 Answer 1

2

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";
    }

}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Rizier123 for adding your contributions to my answer.
You're welcome :) Don't just say to OP to "try something". Always explain why you changed something in OP's code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.