Armstrong Number in Java
Let's write a java program to check whether the given number is armstrong number or not.
Armstrong Number in Java: A positive number is called armstrong number if it is equal to the sum of cubes of its digits for example 0, 1, 153, 370, 371, 407 etc.
Example 1: Check Armstrong Number for 3 digit number
public class Armstrong {
public static void main(String[] args) {
int number = 371, originalNumber, remainder, result = 0;
originalNumber = number;
while (originalNumber != 0)
{
remainder = originalNumber % 10;
result += Math.pow(remainder, 3);
originalNumber /= 10;
}
if(result == number)
System.out.println(number + " is an Armstrong number.");
else
System.out.println(number + " is not an Armstrong number.");
}
}
When you run the program, the output will be:
371 is an Armstrong number.
Example 2: Check Armstrong number for n digits
public class Armstrong {
public static void main(String[] args) {
int number = 1634, originalNumber, remainder, result = 0, n = 0;
originalNumber = number;
for (;originalNumber != 0; originalNumber /= 10, ++n);
originalNumber = number;
for (;originalNumber != 0; originalNumber /= 10)
{
remainder = originalNumber % 10;
result += Math.pow(remainder, n);
}
if(result == number)
System.out.println(number + " is an Armstrong number.");
else
System.out.println(number + " is not an Armstrong number.");
}
}
When you run the program, the output will be:
1634 is an Armstrong number.
0 comments:
Post a Comment