In this article, we will write a program
To print Armstrong numbers from 0 - 500.
Check whether the given number is Armstrong or not.
Let's start with the definition of the Armstrong numbers.
What is Armstrong's Number?
An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself.
For example,
153 = 1*1*1 + 5*5*5 + 3*3*3 = 153
371 = 3*3*3 + 7*7*7 + 1*1*1 = 371
Code:
1. Print Armstrong Numbers from 0 - 500
class Main {
public static void main(String[] args) {
int low = 0, high = 500;
System.out.print("The Armstrong Numbers from 0 - 500 are: ");
for(int number = low + 1; number < high; ++number) {
int digits = 0;
int result = 0;
int originalNumber = number;
// number of digits calculation
while (originalNumber != 0) {
originalNumber /= 10;
++digits;
}
originalNumber = number;
// result contains sum of nth power of its digits
while (originalNumber != 0) {
int remainder = originalNumber % 10;
result += Math.pow(remainder, digits);
originalNumber /= 10;
}
if (result == number) {
System.out.print( number + " ");
}
}
}
}
Output:
2. Check whether the given number is Armstrong or not
import java.util.Scanner;
public class ArmStrong
{
public static void main(String[] args)
{
int n, count = 0, a, b, c, sum = 0;
Scanner s = new Scanner(System.in);
System.out.print("Enter any integer you want to check:");
n = s.nextInt();
a = n;
c = n;
while(a > 0)
{
a = a / 10;
count++;
}
while(n > 0)
{
b = n % 10;
sum = (int) (sum+Math.pow(b, count));
n = n / 10;
}
if(sum == c)
{
System.out.println("Given number is Armstrong");
}
else
{
System.out.println("Given number is not Armstrong");
}
}
}
Output:
The Tech Platform
Comments