Armstrong number is a number that is equal to the sum of cubes of its digits.

For example 0, 1, 153, 370, 371 and 407 are the Armstrong numbers. let take an example of the armstrong number 153.

Sum of the cube of each digit is equal to the same number.

153 = 1^3 + 5^3 + 3^3;

Code Problem

Write a java code for the armstrong number.

Approach

  1. Get the input using the Scanner stdin.
  2. Run a while loop unless the number is greater than zero.
  3. Extract each number.
  4. Find the cube of each number and sum the value.
import java.util.Scanner;

public class Armstrong {
		
	public static void arm(int num) {
		int c=0; 
		int temp; 
		int a;
		
		temp=num;
		while(num > 0) {			
			a = num % 10;
			c = c+(a*a*a);			
			num = num / 10;				
		}
		
		if(temp == c ){
			System.out.println("Armstrong");
		} else {
			System.out.println("Not Armstrong");
		}
				
	}
	
	public static void main(String[] args) {
		System.out.println("Enter number  ");
        Scanner scanner = new Scanner(System.in);
        int cnt = scanner.nextInt();        
        scanner.close();
        
        Armstrong.arm(cnt);
	}
}

Run Code

Similar Posts