Program to check if the given number is Armstrong
Program : Find if the given number is Armstrong
A number is said to be armstrong if the sum of cube of its digits is equal to the number itself.
e.g.
371 is an Armstrong number, since   3^3 + 7^3 + 1^3 = 371
341 is not Armstrong number, since  3^3 + 4^3 + 1^3 = 92
import java.util.Scanner;

class Armstrong{

  public static void main(String args[]){
     Armstrong obj = new Armstrong();
     System.out.println("Enter a number to check Armstrong"); 
     Scanner sc = new Scanner(System.in); 
     obj.isArmstrong(sc.nextInt());
  }

 
  public void isArmstrong(int n){
     int sum = 0,number = n;
     while(n!=0){ 
       sum += Math.pow(n%10,3);
       n = n/10;
     }
     if(sum == number)
       System.out.println("Number "+number+" is Armstrong");
     else
       System.out.println("Number "+number+" is not Armstrong");
     
  }


}
Enter a number to check Armstrong
371
Number 371 is Armstrong

Here we run the while loop while(n!=0) till the value of n does not becomes zero. In the loop we find the last digit of the number by n%2 and add the cube of the digit to the sum. At last if the sum is equal to the sum of cubes of digit we say the number is armstrong.
sum    = 0    digit  = 1 number = 371
sum    = 1    digit  = 7 number = 37
sum    = 344  digit  = 3 number = 3
sum    = 371  digit  = 0 number = 0

No comments :

Post a Comment