Armstrong Number JAVA Program


Armstrong number is a number which is equal to sum of digits raise to the power total number of digits in the number.

Example :

33+ 73 + 13 = 371

14 + 64 + 34 + 44=1634

Below is JAVA program to check Armstrong Number.

import java.util.Scanner;

class ArmstrongNumber {
	public static void main(String args[]) {
	int n, sum = 0, temp, remainder, digits = 0;

	Scanner in = new Scanner(System.in);
	System.out.println("Input a number to check if it is an Armstrong number");
	n = in.nextInt();

	temp = n;

	// Count number of digits

	while (temp != 0) {
		digits++;
		temp = temp / 10;
	}

	temp = n;

	while (temp != 0) {
		remainder = temp % 10;
		sum = sum + power(remainder, digits);
		temp = temp / 10;
	}

	if (n == sum)
		System.out.println(n + " is an Armstrong number.");
	else
		System.out.println(n + " is not an Armstrong number.");
	}

	static int power(int n, int r) {
		int c, p = 1;

		for (c = 1; c <= r; c++)
			p = p * n;

		return p;
	}
}

More Info

For more Algorithms and Java Programing Test questions and sample code follow below links

Advertisements

About Saurabh Gupta

My Name is Saurabh Gupta, I have approx. 11 Year of experience in Information Technology World manly in Java/J2EE. During this time I have worked with multiple organization with different client, so many technology, frameworks etc.
This entry was posted in Algorithm, Complexity, Example, Java and tagged , . Bookmark the permalink.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s