PHP | Check if a number is armstrong number
Last Updated :
30 Apr, 2021
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”.
Php
<?php
function armstrongCheck( $number ){
$sum = 0;
$x = $number ;
while ( $x != 0)
{
$rem = $x % 10;
$sum = $sum + $rem * $rem * $rem ;
$x = $x / 10;
}
if ( $number == $sum )
return 1;
return 0;
}
$number = 407;
$flag = armstrongCheck( $number );
if ( $flag == 1)
echo "Yes" ;
else
echo "No"
?>
|
Output:
Yes
Time Complexity: O(num), where num is the number of digits in the given number.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...