PHP | Check if a number is armstrong number

Given a number, we need to check whether it is an armstrong number or not in PHP. An Armstrong number is the one whose value is equal to the sum of the cubes of its digits.

Examples:

Input : 407
Output : Yes
407 = (4*4*4) + (0*0*0) + (7*7*7)  
    = 64 + 0 + 343  
    = 407  

Input : 303
Output : No



Approach: For every digit r in input number x, compute r3. If sum of all such values is equal to n, then print “Yes”, else “No”.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP code to check wether a number is 
// armstrong number or not
  
// function to check whether the number is 
// armstrong number or not
function armstrongCheck($number){
    $sum = 0;  
    $x = $number;  
    while($x != 0)  
    {  
        $rem = $x % 10;  
        $sum = $sum + $rem*$rem*$rem;  
        $x = $x / 10;  
    }  
      
    // if true then armstrong number
    if ($number == $sum)
        return 1;
      
    // not an armstrong number    
    return 0;    
}
  
// Driver Code
$number = 407;
$flag = armstrongCheck($number);
if ($flag == 1)
    echo "Yes";
else
    echo "No"
?>

chevron_right


Output:

Yes

Time Complexity: O(num), where num is the number of digits in the given number.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.