+1 vote
in Other by
I am just a beginner in php. I have tried to write code for armstrong numbers. I have checked my code by 153. The output of my code is 0.153is not an armstrong number.How can i correct it? Here is my code.

<?php

$n=153;

while($n>1)

{

    $b=$n%10;

    $c=$b*$b*$b;

    $n=$n/10;

    $d=$c+$d;

}

if($d==$n)

    echo $n."is an armstrong number";

else

    echo $n."is not an armstrong number";

?>

JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)

1 Answer

0 votes
by
Given the Armstrong Numbers definition, a functional solution is more concise and a little bit clearer to me

function isArmstrongNumber($number) {

    $digits=str_split($number); // create an array containing the digit into the

    $result = array_sum(

        array_map(

            function($x){return $x*$x*$x;},

            $digit

        )

    );

    return $number == $result;

}

It turns out that the previous definition was valid for number of three digits. A general definition lead to a slight different function:

function isArmstrongNumber($number) {

    $digits=str_split($number); // create an array containing the single digits

    $power= count($digits);     // the power every digit has to be raised to

    $result = array_sum(

        array_map('pow', $digits, array_fill(0,$power,$power))

    );

    return $number == $result;

}

You can use the code in this way:

$candidate = 153;

if(isArmstrongNumber($candidate) {

    /* armstrong number */

    echo $candidate, ' is an Armstrong number.';

} else {

    /* not armstrong number */

    echo $candidate, ' is not an Armstrong number.';

}
...