Armstrong Number

armstrong number
PHP

Armstrong Number

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";  
}  
?>  
  1. Define a number which you want to find Armstrong or not to $num
  2. Declare a variable $sum=0
  3. Copy the $num to a new variable for checking whether the it is Armstrong or not
  4. Loop the $num until its not 0
  5. Get the reminder of $num by $num%10
  6. Find the sum of cube of the reminder and add it with $sum
  7. Divide the $num by 10
  8. 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

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top