# Armstrong Numbers in Java

This is a cool program that displays all of the Armstrong Numbers between 100 and 1000. It can be easily altered to take boundaries from a user and run the program from the suggested lower and upper bounds.

As an aside, I find it amusing that these numbers are also called Narcissistic Numbers, and are part of a branch of mathematics called ‘Recreational Number Theory’ – all I can picture are a bunch of mathematicians lounging on a beach doing math puzzles!

This program was written in Java and executed in Eclipse.

import java.lang.Math; // Import to use the power expression

public class Armstrong

{

public static void main(String[] args)

{

int i, a, b, c, sum=0;

for(i=100; i<=999; i++) /* The upper limit is set to 999 because this code handles three digit numbers, not four! If you entered 1000, then 1000 would show up in the results, and 1000 is not an Armstrong Number*/

{

c=i; // Assigns the counter value to c

a=c%10; // Performs modulo division to remove the last digit from the number to save for later

c=c/10; // This operation leaves the remaining two digits of the number

b=c%10; // Performs modulo division to break up the last two digits and saves the middle digit for later

c=c/10; // This operation leaves the last number, which should be the starting digit of the entire number

sum=(int)Math.pow(a, 3) + (int)Math.pow(b, 3) + (int)Math.pow(c, 3); // Adds each cubed number from the above operations

if(i==sum) // This loop compares the initial counter value to the end result (‘sum’)

System.out.println(i); // The value is printed if the two numbers are identical

}

}

}

//——————————————————————————-//

//

// Example of how this math works:

// If c = 100, then:

// 100 MOD 10 = 0 (The last digit of c)

// 100/10 = 10

// 10 MOD 10 = 0 (The middle digit of c)

// 10/10 = 1 (The first digit of c)

// Now that the number has been broken up, math can be performed on the individual numbers while the whole remains intact

Posted on March 29, 2011, in Java. Bookmark the permalink. 2 Comments.

wonderful thnx a lot

Thanks for checking out the post!