Skip to content

Instantly share code, notes, and snippets.

@eMahtab
Created November 19, 2015 06:22
Show Gist options
  • Save eMahtab/d74baf8fd5ff02a17695 to your computer and use it in GitHub Desktop.
Save eMahtab/d74baf8fd5ff02a17695 to your computer and use it in GitHub Desktop.
Java Program for calculating Armstrong number. 153 is an armstrong number as 1^(number of digits)+5^(number of digits)+3^(number of digits)=153. Similarly 371 is an armstrong number 3^(number of digits)+7^(number of digits)+1^(number of digits)=371.
import java.util.Scanner;
import java.util.InputMismatchException;
public class Armstrong{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.print("Enter a number : ");
long input=-999,number=-999,copyOfInput=-999;
try{
input=sc.nextLong();
number=input;
copyOfInput=input;
}catch(InputMismatchException ime){
System.err.println("Error : Please enter a valid number ");
System.exit(1);
}
// To count the number of digits in the number, it will be needed for armstrong calculation
int numberOfDigits=0;
while(number >0){
numberOfDigits++;
number=number/10;
}
// Actual Armstrong Calculation
long sum=0;int remainder=0;
while(input >0){
remainder=(int)input%10;
sum=sum+(long)Math.pow(remainder,numberOfDigits);
input=input/10;
}
if(copyOfInput == sum){
System.out.println("Number "+copyOfInput+" is an Armstrong Number");
}else{
System.out.println("Number "+copyOfInput+" is not an Armstrong Number");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment