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.
370you do:3^3 + 7^3which already is equal to370and you print the number out in your foreach loop. But adding0^3to370in the next and last iteration still is equal to370and you output the number again.ifto after the inner loop.