Introduction

A Harshad number (also widely known as a Niven number) is refreshingly one of the simplest "special number" checks in this entire series. After everything you've learned about digit sums, it comes down to a single, straightforward divisibility test.

If you've already implemented the sum of digits earlier in this series, you're most of the way to solving this problem already, making it a great confidence-building exercise after some of the more intricate special-number checks like Armstrong or Happy numbers.

In this guide, you'll learn:

Advertisement
  • What a Harshad (Niven) number is
  • How to check it using a while loop
  • How to solve it using recursion
  • How to print all Harshad numbers within a range
  • How to correctly handle zero and negative numbers
  • Common mistakes, interview tips, best practices, and FAQs

What Is a Harshad Number? (Also Known as a Niven Number)

A Harshad number is a number that is evenly divisible by the sum of its own digits.

The name Harshad comes from Sanskrit, roughly meaning "great joy." It is also commonly known as a Niven number, named after mathematician Ivan Niven.

For example, consider 18.

Its digit sum is:

 
1 + 8 = 9
 

Now check the divisibility:

 
18 % 9 = 0
 

Since 18 is exactly divisible by 9, 18 is a Harshad number.

Now consider 19.

Its digit sum is:

 
1 + 9 = 10
 

Checking divisibility:

 
19 % 10 = 9
 

Since the remainder is not zero, 19 is not a Harshad number.


Method 1: Using a While Loop

This is the standard and most commonly used approach.

The idea is simple:

  1. Calculate the sum of the digits.
  2. Check whether the original number is divisible by that sum.
 
public class HarshadNumberCheck {

    public static void main(String[] args) {

        int num = 18;
        int original = num;
        int sum = 0;

        while (num != 0) {
            int digit = num % 10;
            sum += digit;
            num /= 10;
        }

        if (original % sum == 0) {
            System.out.println(original + " is a Harshad number.");
        } else {
            System.out.println(original + " is not a Harshad number.");
        }
    }
}
 

How This Works

The algorithm performs two simple tasks.

First, it calculates the sum of all digits.

For the number 18:

 
num = 18

digit = 8
sum = 8

digit = 1
sum = 9

num = 0
 

Once the digit-sum loop finishes:

 
sum = 9
 

The program then performs the divisibility check:

 
18 % 9 == 0
 

Since the remainder is 0, the program concludes that 18 is a Harshad number.


Step-by-Step Trace

For num = 18:

Iteration Digit Extracted Running Sum Remaining Number
1 8 8 1
2 1 9 0

After the loop:

 
Digit Sum = 9
18 % 9 = 0
 

Therefore:

18 is a Harshad number.


Output

 
18 is a Harshad number.
 

Why We Preserve the Original Number

Just like the palindrome, Armstrong, and several other digit-based problems in this series, the digit extraction process gradually destroys the original value.

For example:

 
18
↓
1
↓
0
 

After the loop finishes, num becomes 0.

If you attempted the divisibility check using num instead of the original value:

 
num % sum
 

you would actually be checking:

 
0 % 9
 

which is not the intended calculation.

To avoid this problem, the program stores the original value before digit extraction begins:

 
int original = num;
 

After calculating the digit sum, the divisibility test correctly uses:

 
original % sum == 0
 

This same pattern appears throughout many digit-manipulation programs because the extraction loop always reduces the working variable to zero.


Method 2: Using Recursion

Instead of calculating the digit sum with a loop, we can reuse the familiar recursive sum-of-digits pattern.

The recursive method computes the digit sum, after which the divisibility check remains exactly the same.

 
public class HarshadNumberRecursion {

    static int sumOfDigits(int n) {

        if (n == 0) {
            return 0;
        }

        return (n % 10) + sumOfDigits(n / 10);
    }

    public static void main(String[] args) {

        int num = 18;
        int sum = sumOfDigits(num);

        if (num % sum == 0) {
            System.out.println(num + " is a Harshad number.");
        } else {
            System.out.println(num + " is not a Harshad number.");
        }
    }
}
 

How This Works

The recursive method repeatedly separates the last digit and adds it to the result of the remaining digits.

For 18, the recursive calls happen like this:

 
sumOfDigits(18)
= 8 + sumOfDigits(1)

= 8 + (1 + sumOfDigits(0))

= 8 + 1 + 0

= 9
 

Once the digit sum is calculated, the program performs the same divisibility check:

 
18 % 9 == 0
 

Since the remainder is zero, the program concludes that 18 is a Harshad number.

This is a clean and reusable approach that demonstrates how mastering a simple recursive helper function can solve multiple digit-based problems throughout this series.

Method 3: Printing All Harshad Numbers in a Range

To find every Harshad number within a range, place the Harshad number check inside a reusable method and call it for every number in the specified range.

 
public class HarshadNumbersInRange {

    static boolean isHarshad(int num) {

        int sum = 0;
        int temp = num;

        while (temp != 0) {
            sum += temp % 10;
            temp /= 10;
        }

        return num % sum == 0;
    }

    public static void main(String[] args) {

        int start = 1;
        int end = 50;

        System.out.println("Harshad numbers between " + start + " and " + end + ":");

        for (int num = start; num <= end; num++) {
            if (isHarshad(num)) {
                System.out.print(num + " ");
            }
        }
    }
}
 

Output

 
Harshad numbers between 1 and 50:
1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 45 48
 

How This Works

Instead of checking a single number, the program loops through every number between the starting and ending values.

For each number:

  1. The isHarshad() method calculates the digit sum.
  2. It checks whether the number is evenly divisible by that digit sum.
  3. If the method returns true, the number is printed.
  4. Otherwise, the program continues with the next number.

This approach keeps the checking logic reusable while making it easy to print Harshad numbers within any range.

Why Are Harshad Numbers So Common?

Compared to special numbers like Armstrong numbers, Strong numbers, or Happy numbers, Harshad numbers are surprisingly common.

There are two main reasons:

  • Every single-digit number is automatically a Harshad number because a single digit is always divisible by itself.
  • Many multi-digit numbers also satisfy the divisibility rule since dividing by the sum of digits is much less restrictive than matching powers or factorials.

For example:

Number Digit Sum Divisible? Harshad?
12 3 12 ÷ 3 = 4 ✅ Yes
18 9 18 ÷ 9 = 2 ✅ Yes
20 2 20 ÷ 2 = 10 ✅ Yes
19 10 19 ÷ 10 = 1 remainder 9 ❌ No

Handling Zero and Negative Numbers

Although the basic algorithm is simple, two important edge cases deserve special attention.

Edge Case 1: Zero

Suppose the input is:

 
0
 

The digit-sum loop looks like this:

 
while (num != 0)
 

Since num is already 0, the loop never executes.

As a result:

 
sum = 0
 

Now the program attempts:

 
original % sum
 

which becomes:

 
0 % 0
 

This causes Java to throw an ArithmeticException because division (or modulus) by zero is not allowed.

Therefore, production-quality code should explicitly handle zero before performing the divisibility check.

Most implementations simply treat 0 as not being a Harshad number.


Edge Case 2: Negative Numbers

Negative numbers require special handling because Java's modulus operator returns negative remainders for negative operands.

For example:

 
-18 % 10 = -8
 

This produces incorrect digit sums if processed directly.

Instead, convert the number to its absolute value before extracting digits:

 
int original = Math.abs(num);
 

Now the digit extraction works correctly regardless of whether the input is positive or negative.


Safe Implementation (Handles Both Edge Cases)

 
public class HarshadNumberSafe {

    static boolean isHarshad(int num) {

        if (num == 0) {
            return false;
        }

        int original = Math.abs(num);

        int sum = 0;
        int temp = original;

        while (temp != 0) {
            sum += temp % 10;
            temp /= 10;
        }

        return original % sum == 0;
    }

    public static void main(String[] args) {

        int num = -18;

        System.out.println(
                num + (isHarshad(num)
                        ? " is a Harshad number."
                        : " is not a Harshad number.")
        );
    }
}
 

How This Improved Version Works

The safe implementation introduces two small but important improvements.

First, it prevents division by zero:

 
if (num == 0) {
    return false;
}
 

Second, it removes the sign before processing digits:

 
int original = Math.abs(num);
 

The remaining logic stays exactly the same.

These two checks make the program suitable for handling any integer input, not just positive numbers.


How Java Handles This Internally (Memory Concept)

Understanding what happens internally helps explain why this program is both simple and efficient.

Methods 1 and 3

The following variables are all primitive int values:

  • num
  • original
  • temp
  • sum
  • digit

These variables are stored inside the stack frame of the currently executing method.

During the divisibility check:

 
original % sum
 

Java performs the modulus operation directly on primitive integer values without creating any additional objects.

No heap memory is required.


Method 2 (Recursion)

The recursive version behaves slightly differently.

Each call to:

 
sumOfDigits(n)
 

creates a new stack frame containing:

  • n
  • the return address
  • local execution information

As the recursion progresses, additional stack frames are created until the base case is reached.

After reaching:

 
n == 0
 

the recursive calls begin returning one by one until the original call completes.

This is the same recursive execution pattern used in several other digit-based problems throughout this series.


Heap Memory Usage

None of these implementations allocate objects dynamically.

There are:

  • No arrays
  • No collections
  • No strings created during the algorithm
  • No custom objects

Everything operates using primitive integer variables.

As a result, the Harshad number check is both memory-efficient and computationally inexpensive.

 

Real-Life Analogy: A Team Size That Divides Evenly Into the Total Project Hours

Imagine a project requires 18 hours of work.

Now imagine the team size is determined by the sum of the digits of the total hours.

For 18 hours:

 
1 + 8 = 9 team members
 

Can the work be divided evenly among all team members?

 
18 ÷ 9 = 2 hours per person
 

Since every team member receives exactly 2 hours of work with nothing left over, the division is perfectly even.

That is exactly how a Harshad number works.

The total number is evenly divisible by the sum of its own digits.

If the work could not be divided evenly—for example, if some hours were left over—it would not be a Harshad number.


Comparison Table of All Methods

Method Handles Zero Safely? Handles Negative Numbers Safely? Best Used When
Basic While Loop ❌ No – risks division by zero ❌ No – requires Math.abs() Simple positive integer examples and beginner programs
Recursion ❌ No – same division-by-zero risk ❌ No – requires Math.abs() Reusing an existing recursive digit-sum method
Safe Version ✅ Yes ✅ Yes Production-quality code that handles all integer inputs safely

Best Practices

Following these best practices will help you write cleaner, safer, and more reusable Harshad number programs.

  • Always handle zero as a special case before performing the divisibility check, since dividing by a digit sum of zero causes an ArithmeticException.
  • Always process the absolute value of negative numbers using Math.abs() before extracting digits.
  • Reuse a well-tested sum-of-digits helper method whenever possible instead of rewriting the digit-sum logic in multiple places.
  • Remember that Harshad numbers are much more common than many other special numbers, such as Armstrong or Strong numbers, so don't expect only a handful of values in larger ranges.
  • Wrap the checking logic inside a reusable method such as:
 
boolean isHarshad(int num)
 

This improves readability, reusability, and maintainability.

  • Test your implementation using different categories of inputs:
    • Single-digit numbers
    • Multi-digit Harshad numbers
    • Non-Harshad numbers
    • Zero
    • Negative numbers

Comprehensive testing helps ensure your implementation handles every important case correctly.


Common Mistakes Beginners Make

Even though the algorithm is simple, beginners often make a few common mistakes.

1. Not Handling Zero

Many beginners forget that the digit sum of 0 is also 0.

As a result, they write:

 
original % sum
 

which becomes:

 
0 % 0
 

This throws an ArithmeticException.

Always check for zero before performing the modulus operation.


2. Forgetting to Handle Negative Numbers

Java returns negative remainders for negative operands.

For example:

 
-18 % 10 = -8
 

If you directly add these values while computing the digit sum, the result becomes incorrect.

Always convert the number using:

 
Math.abs(num)
 

before extracting digits.


3. Confusing Harshad Numbers with Armstrong Numbers

Some beginners accidentally calculate:

 
1³ + 8³
 

or

 
1² + 8²
 

instead of simply calculating:

 
1 + 8
 

Remember:

  • Harshad numbers use the sum of digits.
  • Armstrong numbers use the sum of powered digits.

These are completely different mathematical definitions.


4. Reversing the Divisibility Check

The correct condition is:

 
original % sum == 0
 

Some beginners accidentally write:

 
sum % original == 0
 

This reverses the divisibility test and produces incorrect results for most inputs.


5. Not Testing Single-Digit Numbers

Every positive single-digit number is automatically a Harshad number because:

 
Digit Sum = Number
 

Therefore:

 
Number % Number = 0
 

Testing values from 1 to 9 is an excellent way to verify that your implementation works correctly before trying larger numbers.


Expert Tips for Interviews

A strong interview answer explains both the algorithm and the important edge cases.

A good response might sound like this:

"A Harshad number is a number that's evenly divisible by the sum of its own digits. I first calculate the digit sum using modulus and division, then check whether the original number is divisible by that sum. I'd also handle zero explicitly to avoid division by zero and process negative numbers using Math.abs() so that digit extraction works correctly regardless of the input sign."

Mentioning both zero handling and negative-number handling without being prompted demonstrates defensive programming and attention to detail—qualities that interviewers often value highly.


Pros and Cons

Basic While Loop

Pros

  • ✅ Very easy to understand
  • ✅ Simple to implement
  • ✅ Ideal for beginners
  • ✅ Uses only primitive variables

Cons

  • ❌ Does not handle zero safely
  • ❌ Produces incorrect results for negative numbers unless additional checks are added

Recursion

Pros

  • ✅ Reuses a familiar recursive digit-sum method
  • ✅ Clean and concise implementation
  • ✅ Demonstrates understanding of recursion

Cons

  • ❌ Has the same edge-case limitations as the basic loop
  • ❌ Uses additional stack frames due to recursive calls
  • ❌ Slightly less efficient than the iterative approach for large inputs

Safe Version

Pros

  • ✅ Handles zero safely
  • ✅ Correctly processes negative numbers
  • ✅ Suitable for production-quality applications
  • ✅ More robust and reliable

Cons

  • ❌ Slightly longer than the basic implementation
  • ❌ Includes additional validation logic, although the extra code is generally worthwhile for improved reliability