Armstrong number or Narcissistic number is a positive number where the sum of cubes of every digit in number is equal to its original value. For example 0, 1, 153, 370, 371, 407 and so on.
Let's try to understand why 153 is an Armstrong number.
Example : 153 = (1*1*1)+(5*5*5)+(3*3*3)
where:
(1*1*1)=1
(5*5*5)=125
(3*3*3)=27
So:
1+125+27=153
Lets see how to check if a number is Armstrong number or number in Java:
Finding Armstrong numbers between the given range.
Let's try to understand why 153 is an Armstrong number.
Example : 153 = (1*1*1)+(5*5*5)+(3*3*3)
where:
(1*1*1)=1
(5*5*5)=125
(3*3*3)=27
So:
1+125+27=153
Lets see how to check if a number is Armstrong number or number in Java:
import java.util.Scanner;
public class Armstrong{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int a, b = 0;
int temp=num;
while(num>0){
a = num%10;
num = num/10;
b = b +(a*a*a);
}
if(temp == b){
System.out.println(b+" is a Armstrong Number");
}else{
System.out.println(b+" is not a Armstrong Number");
}
}
}
Finding Armstrong numbers between the given range.
import java.util.Scanner;
public class Armstrong{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
int num1 = sc.nextInt();
int num2 = sc.nextInt();
//Take the sample input as 365 and 375
for(int i = num1; i <= num2; i++){
int a, b = 0;
int num=i;
int temp=num;
while(num>0){
a = num%10;
num = num/10;
b = b +(a*a*a);
}
if(temp==b){
System.out.println("ARMSTRONG Number = "+b);
}
}
}
}
Comments
Post a Comment