Java Tutorial
🔍

Special Number Programs in Java Explained

Special Numbers in Java

Armstrong numbers, perfect numbers, Harshad numbers, neon numbers — Java courses and coding tests are full of "is this a ___ number?" questions. They look like dozens of separate puzzles, but they're built from only a handful of techniques: pulling digits out of a number, adding up divisors, testing for primes, and repeating a step until a pattern appears. Learn those techniques once and every special-number program becomes a short combination of them.

The Core Toolkit: Working with Digits

Most special numbers are defined by their digits. Two operators do almost all the work:

  • ›n % 10 gives the last digit.
  • ›n / 10 removes the last digit (integer division drops the remainder).

Repeating those two steps in a loop visits every digit from right to left:

1public class DigitToolkit { 2 public static void main(String[] args) { 3 int n = 4729; 4 5 int sum = 0, product = 1, count = 0; 6 for (int t = n; t > 0; t /= 10) { // work on a copy so n stays unchanged 7 int digit = t % 10; 8 sum += digit; 9 product *= digit; 10 count++; 11 } 12 13 int reversed = 0; 14 for (int t = n; t > 0; t /= 10) { 15 reversed = reversed * 10 + t % 10; // shift left, append the digit 16 } 17 18 System.out.println("Digits: " + count); 19 System.out.println("Sum: " + sum + ", product: " + product); 20 System.out.println("Reversed: " + reversed); 21 } 22}

Output:

Digits: 4 Sum: 22, product: 504 Reversed: 9274

Always loop over a copy (t) of the number. Many special-number checks compare the result with the original value, and the loop would otherwise have reduced it to 0.

Family 1: Numbers Defined by Digit Powers and Factorials

These numbers equal a sum built from their own digits.

NumberRuleExample
ArmstrongSum of each digit raised to the power of the digit count153 = 1³ + 5³ + 3³
DisariumSum of each digit raised to its position (1, 2, 3 … from the left)89 = 8¹ + 9²
StrongSum of the factorials of the digits145 = 1! + 4! + 5!

The pattern is the same for all three: extract each digit, transform it (a power or a factorial), add the results, and compare the total with the original number. The only difference is the transformation — and for Disarium, the position must be counted from the left, so it's easiest to work with the digit count or the number as a string.

The four 3-digit Armstrong numbers are 153, 370, 371 and 407.

Family 2: Numbers Defined by Digit Sums and Products

NumberRuleExample
Harshad (Niven)Divisible by the sum of its digits18: digit sum 9, and 18 ÷ 9 = 2
NeonThe digit sum of its square equals the number9² = 81, and 8 + 1 = 9
SpyDigit sum equals digit product1124: 1+1+2+4 = 8 and 1×1×2×4 = 8
MagicRepeated digit sums end at 119 → 10 → 1
DuckContains a zero digit (not at the start)1023

These only need the digit loop from the toolkit, sometimes applied to a derived value such as the square (Neon) or repeated until one digit remains (Magic).

Family 3: Numbers Defined by Divisors

A proper divisor of n is any divisor smaller than n itself. Comparing the sum of proper divisors with n sorts every number into one of three groups:

NumberRuleExample
PerfectSum of proper divisors equals n28 = 1 + 2 + 4 + 7 + 14
AbundantSum is greater than n12: 1+2+3+4+6 = 16
DeficientSum is less than n8: 1+2+4 = 7

The simple way loops i from 1 to n - 1. The faster way loops only up to √n and adds both i and n / i whenever i divides n, because divisors come in pairs — taking care not to add the square root twice, or n itself.

Family 4: Numbers Built on Primes

NumberRuleExample
Twin primesTwo primes that differ by 241 and 43
Co-primeTwo numbers whose GCD is 18 and 15
Circular primeEvery rotation of its digits is prime197, 971, 719
EmirpPrime whose reversed digits form a different prime13 and 31

Each one starts from a single helper — a prime test that tries divisors up to √n — combined with a second step: comparing two primes, computing a GCD, rotating digits, or reversing them. Writing isPrime once as its own method keeps all four programs short.

Family 5: Numbers That Reproduce Themselves

NumberRuleExample
AutomorphicIts square ends with the number itself76² = 5776
KaprekarSplit its square into two parts that add back to the number45² = 2025, and 20 + 25 = 45
KeithAppears in a Fibonacci-like sequence seeded by its digits14: 1, 4, 5, 9, 14
HappyRepeatedly summing the squares of its digits reaches 119 → 82 → 68 → 100 → 1
PalindromicReads the same reversed12321

For the "repeat until" checks, such as Happy and Magic, make sure the loop can end. Unhappy numbers never reach 1 — they fall into a cycle that always passes through 4 — so the loop must stop on 1 or on 4 (or track the values it has already seen).

Family 6: Numbers Defined in Binary

NumberRuleExample
EvilEven number of 1 bits in binary5 = 101 (two 1s)
OdiousOdd number of 1 bits in binary7 = 111 (three 1s)

Integer.bitCount(n) counts the 1 bits directly. Without it, use n % 2 and n / 2 — the binary version of the digit loop above.

Common Mistakes

Mistake 1 — Destroying the Original Number

Running while (n > 0) { ...; n /= 10; } and then comparing the result with n always compares against 0. Copy the number into a separate variable before taking it apart.

Mistake 2 — Using Math.pow for Integer Powers

Math.pow returns a double. For large values the result can be off by a tiny rounding error, and an equality check then fails. Multiply in a small loop, or cast with rounding: (int) Math.round(Math.pow(d, k)).

Mistake 3 — Infinite Loops in Repeated Checks

A happy-number check written as while (n != 1) never ends for an unhappy number. Every "repeat until" check needs a second exit condition for the case where the target is never reached.

Mistake 4 — Counting n as Its Own Divisor

Perfect, abundant and deficient numbers use proper divisors only. Including n itself makes every number look abundant.

Interview Questions

How do you count the digits of a number without converting it to a string?

Divide by 10 in a loop and count the iterations, treating 0 as one digit. Alternatively, (int) Math.log10(n) + 1 works for positive numbers.

What's the difference between an Armstrong number and a Disarium number?

Armstrong raises every digit to the same power — the digit count. Disarium raises each digit to its own position from the left, so the power changes from digit to digit.

Why are prime checks done only up to the square root?

If n had a factor larger than √n, the matching factor would be smaller than √n and would already have been found. Stopping at √n turns an O(n) check into O(√n).

FAQs

Are these special numbers used in real software?

Rarely as-is, but the techniques are everywhere: digit extraction appears in checksums such as credit-card and ISBN validation, divisor sums in number theory, and bit counting in compression and cryptography.

Which special numbers are asked most often?

Armstrong, perfect, prime, palindrome and Fibonacci numbers come up most, followed by strong, Harshad, neon and happy numbers.

Should I use int or long?

int is fine for the examples here. Squares and powers grow fast, though — Neon, Automorphic and Kaprekar checks square the number, so use long once inputs go beyond about 46,000.

Summary

Special-number questions reduce to a few reusable techniques: extract digits with % 10 and / 10, sum proper divisors, test primality up to √n, repeat a transformation until it reaches a target or cycles, and count bits in binary. Each family above is one of those techniques plus a comparison. Use the practice programs below to try each one.

What to Read Next

Practice Programs

Put this topic into practice — each program has full code, output and a step-by-step explanation you can run online.

Show all 38 practice programs ↓
Numbersbeginner
Check Magic Number

Determines whether a number is a magic number.

Control Flowbeginner
Check Number Duck

Determines whether a number contains a zero digit anywhere in it.

Numbersbeginner
Check Abundant Number

Determines whether a number's proper divisors add up to more than the number itself.

Numbersbeginner
Check Deficient Number

Determines whether a number's proper divisors add up to less than the number itself.

Numbersbeginner
Check Twin Prime

Determines whether two numbers form a twin prime pair.

Numbersbeginner
Check Co-Prime Numbers

Determines whether two numbers share no common factor besides 1.

Numbersintermediate
Check Circular Prime

Determines whether every digit-rotation of a number is also prime.

Numbersintermediate
Check Emirp Number

Determines whether a number is prime, and its digit-reversal is a different prime.

Numbersintermediate
Check Kaprekar Number

Determines whether a number is a Kaprekar number.

Numbersadvanced
Check Keith Number

Determines whether a number reappears in a Fibonacci-like sequence seeded by its own digits.

Numbersbeginner
Check Evil Number

Determines whether a number's binary representation has an even number of 1 bits.

Numbersbeginner
Check Odious Number

Determines whether a number's binary representation has an odd number of 1 bits.

Numbersintermediate
Check Fibonacci Number

Determines whether a given number is itself a Fibonacci number.

Numbersbeginner
Print Armstrong Numbers in a Range

Lists every Armstrong number within a given range.

Numbersintermediate
Print Perfect Numbers

Lists every perfect number within a range.

Numbersintermediate
Print Strong Numbers in a Range

Lists every strong number within a given range.

Numbersintermediate
Print Happy Numbers in a Range

Lists every happy number within a given range.

Numbersbeginner
Print Automorphic Numbers in a Range

Lists every automorphic number within a given range.

Numbersintermediate
Print Twin Primes

Lists every twin prime pair up to a given limit.

Numbersbeginner
Print Prime Numbers in a Range

Lists every prime number between a lower and upper bound.

Numbersbeginner
Count Prime Numbers in a Range

Counts how many prime numbers fall between a lower and upper bound.

Numbersbeginner
Find Sum of Prime Numbers

Adds up every prime number within a range.

Numbersintermediate
Prime Factorization

Breaks a number down into its full product of prime factors.

Numbersintermediate
Find Largest Prime Factor

Finds the biggest prime number that divides a number evenly.

Numbersbeginner
Find Smallest Prime Factor

Finds the smallest prime number that divides a number evenly.

Numbersbeginner
Find GCD (Euclidean Algorithm)

Finds the greatest common divisor of two numbers.

Numbersbeginner
Find LCM (Using GCD)

Finds the least common multiple of two numbers.

Control Flowintermediate
Calculate Digital Root

Reduces a number down to a single digit by repeatedly summing its digits.

Browse all Java programs →