Write a php program to find the number is an Armstrong Number or not
If the sum of the cubes of the digits of a number is equal to the number then its called an Armstrong number .
Eg:- 153
(1*1*1)+(5*5*5)+(3*3*3) = 1+125+27 = 153
Program :
<?php
$num=153;
$sum=0;
$num_copy=$num;
while($num!=0)
{
$rem=$num%10;
$sum=$sum+$rem*$rem*$rem;
$num=$num/10;
}
if($num_copy==$sum)
{
echo "Yes $num_copy is an Armstrong number";
}
else
{
echo "No $num_copy is not an Armstrong number";
}
?>
- Define a number which you want to find Armstrong or not to $num
- Declare a variable $sum=0
- Copy the $num to a new variable for checking whether the it is Armstrong or not
- Loop the $num until its not 0
- Get the reminder of $num by $num%10
- Find the sum of cube of the reminder and add it with $sum
- Divide the $num by 10
- If the $num_copy ==$sum then the number is Armstrong
Logic :
$num = 153
$num_copy = $num, ie; $num_copy = 153
1st loop
$sum = 0
while(153!=0)
{
$rem = $num%10 = 153 % 10 = 3
$sum = $sum+$rem * $rem * $rem = 0 + 3*3*3 = 0+27 = 27
$num = $num/10 = 153/10= 15
}
2nd loop
$sum = 27
while(15!=0)
{
$rem = $num%10 = 15 % 10 = 5
$sum = $sum+$rem * $rem * $rem = 27 + 5*5*5 = 27+125 = 152
$num = $num/10 = 15/10= 1
}
3rd loop
$sum = 152
while(1!=0)
{
$rem = $num%10 = 1 % 10 = 1
$sum = $sum+$rem * $rem * $rem = 152 + 1*1*1 = 152+1 = 153
$num = $num/10 = 1/10= 0.1
}
Note : When we give the variable directly in the ” “, it will display the value of that variable.
Click here for the program factorial in php
Click here for more knowledge on Armstrong number