Day 9–15: Number Property Programs in Java (Using while
Loops)
We’ll implement seven classic checks, each in its own static method within a single Java class. All loops use only while
, and no built‐ins beyond basic arithmetic.
1. Armstrong Number
An Armstrong number (for a given number of digits) equals the sum of each digit raised to the power of the number of digits.
public static boolean isArmstrong(int num) {
int original = num, sum = 0, digits = 0;
int temp = num;
// Count digits
while (temp > 0) {
digits++;
temp /= 10;
}
temp = original;
// Sum of powers
while (temp > 0) {
int d = temp % 10;
int power = 1;
int i = 0;
while (i < digits) {
power *= d;
i++;
}
sum += power;
temp /= 10;
}
return sum == original;
}
2. Neon Number
A Neon number is one where the square of the number’s sum of digits equals the number.
public static boolean isNeon(int num) {
int square = num * num;
int sum = 0;
while (square > 0) {
sum += square % 10;
square /= 10;
}
return sum == num;
}
3. Strong Number
A Strong number equals the sum of factorials of its digits.
public static int factorial(int n) {
int fact = 1;
while (n > 0) {
fact *= n;
n--;
}
return fact;
}
public static boolean isStrong(int num) {
int temp = num, sum = 0;
while (temp > 0) {
sum += factorial(temp % 10);
temp /= 10;
}
return sum == num;
}
4. Perfect Number
A Perfect number equals the sum of its proper divisors (excluding itself).
public static boolean isPerfect(int num) {
int sum = 0;
int i = 1;
while (i < num) {
if (num % i == 0) {
sum += i;
}
i++;
}
return sum == num;
}
5. Prime and Composite
A prime has exactly two divisors (1 and itself). A composite (non-prime greater than 1) has more.
public static boolean isPrime(int num) {
if (num <= 1) return false;
int i = 2;
while (i * i <= num) {
if (num % i == 0) return false;
i++;
}
return true;
}
6. Emirp Number
An Emirp is a prime that yields a different prime when its decimal digits are reversed.
public static int reverseNumber(int num) {
int rev = 0;
while (num > 0) {
rev = rev * 10 + (num % 10);
num /= 10;
}
return rev;
}
public static boolean isEmirp(int num) {
if (!isPrime(num)) return false;
int rev = reverseNumber(num);
return rev != num && isPrime(rev);
}
Top comments (0)