Harshad Number in Java: Niven Number Check With Examples

Check a Harshad number in Java with a digit-sum loop that never divides by zero, try other bases, count Harshad numbers and build a lucky-draw rule.

Flow for 156 and 47 that adds the digits and tests the remainder of the number divided by the digit sum

A Harshad number, also called a Niven number, is a positive integer that is divisible by the sum of its digits. For example, 156 is a Harshad number because 1 + 5 + 6 = 12, and 156 = 12 x 13 leaves no remainder. A Harshad number in Java takes one digit-sum loop and one remainder test to check.

Harshad numbers are a standard exercise for reading digits with % 10 and / 10, and the same digit-sum code shows up in check-digit validation and in promotional rules that depend on a ticket or receipt number.

The following example computes the digit sum of 156 from its characters and tests the remainder.

int number = 156;
int digitSum = String.valueOf(number).chars().map(c -> c - '0').sum();   // 12
boolean harshad = number % digitSum == 0;                               // true

Once the digit sum is known, the check is a single remainder test. We cover the arithmetic loop and the input that makes it crash, Harshad numbers in other bases, how many exist in a range, and a lucky-draw rule built on the check.

1. Harshad Number Definition and Examples

The Indian mathematician D. R. Kaprekar named these numbers “Harshad”, from the Sanskrit words for “joy” and “giver”. The English name Niven number comes from the mathematician Ivan Niven. Both names mean the same thing in base 10.

Flow for 156 and 47 that adds the digits and tests the remainder of the number divided by the digit sum
Adding the digits and testing one remainder decides the result, so 156 is Harshad and 47 is not

The rule has two steps, add the digits and divide the number by that sum. A zero remainder means Harshad, and anything else means it is not.

NumberDigit sumDivisionHarshad
181 + 8 = 918 / 9 = 2Yes
404 + 0 = 440 / 4 = 10Yes
1561 + 5 + 6 = 12156 / 12 = 13Yes
474 + 7 = 1147 / 11 = 4, remainder 3No
191 + 9 = 1019 / 10 = 1, remainder 9No

Every number from 1 to 10 is a Harshad number, because a single digit divides itself and 10 has the digit sum 1. The sequence continues with 12, 18, 20, 21, 24, 27 and 30, as listed in OEIS A005349.

2. Harshad Number Program in Java

The arithmetic version takes the last digit with % 10, adds it to a sum and drops it with / 10. The loop changes its working variable, so the original number must stay in a separate variable for the final remainder test.

2.1. The Digit-Sum Loop and the Division by Zero

A direct translation of the rule works for every positive number. The problem is 0 and negative input, where the loop condition temp > 0 is false from the start, the digit sum stays 0, and the remainder operation divides by zero.

static boolean isHarshadUnsafe(int number) {
    int temp = number;
    int digitSum = 0;
    while (temp > 0) {
        digitSum += temp % 10;
        temp /= 10;
    }
    return number % digitSum == 0;
}
boolean h40 = isHarshadUnsafe(40);     // true
boolean h47 = isHarshadUnsafe(47);     // false
boolean h0 = isHarshadUnsafe(0);       // ArithmeticException: / by zero

Always reject 0 and negative numbers before dividing by the digit sum. The definition covers positive integers only, so the safe version returns false for them and accepts any long.

static boolean isHarshad(long number) {
    if (number <= 0) {
        return false;
    }
    long digitSum = 0;
    for (long temp = number; temp > 0; temp /= 10) {
        digitSum += temp % 10;
    }
    return number % digitSum == 0;
}
boolean safe0 = isHarshad(0);                         // false
boolean safeNeg = isHarshad(-18);                     // false
boolean h1729 = isHarshad(1729);                      // true
boolean bigOne = isHarshad(1_000_000_000_000_000L);   // true

The taxicab number 1729 has the digit sum 19, and 1729 = 19 x 91. Every power of 10 is a Harshad number, because its digit sum is 1. A common bug in published solutions is to divide the loop variable after the loop instead of the original number. After the loop, that variable is 0, so 0 % digitSum is always 0 and every input looks like a Harshad number.

2.2. Reading the Digits as Characters

The string version converts the number with Long.toString() and adds c – ‘0’ for every character. The code is shorter, it creates a String for every call, and it needs the same guard for 0 and negative numbers, because a minus sign is not a digit.

static boolean isHarshadText(long number) {
    if (number <= 0) {
        return false;
    }
    int digitSum = Long.toString(number).chars().map(c -> c - '0').sum();
    return number % digitSum == 0;
}
boolean t156 = isHarshadText(156);    // true
boolean t19 = isHarshadText(19);      // false

For a single check, readability decides which version to use. In a loop over millions of numbers, the arithmetic version avoids creating millions of short-lived strings.

3. Harshad Numbers in Other Bases

The definition depends on the base, because the digits do. A number is an n-Harshad number when it is divisible by the sum of its digits written in base n. The loop from section 2 needs one change, dividing by the base instead of 10.

static boolean isHarshad(long number, int base) {
    if (number <= 0 || base < 2) {
        return false;
    }
    long digitSum = 0;
    for (long temp = number; temp > 0; temp /= base) {
        digitSum += temp % base;
    }
    return number % digitSum == 0;
}
String binary = Long.toString(12, 2);       // "1100"
boolean base2 = isHarshad(12, 2);           // true
boolean base10 = isHarshad(11, 10);         // false
boolean base3 = isHarshad(11, 3);           // false

In binary, 12 is 1100 with the digit sum 2, so 12 is a 2-Harshad number. Numbers that are Harshad in every base are called all-Harshad numbers, and there are only four of them. A number is a single digit in any base larger than itself, so checking the bases from 2 to the number is enough.

List<Long> allHarshad = LongStream.rangeClosed(1, 1_000).filter(n -> IntStream.rangeClosed(2, (int) Math.max(2, n)).allMatch(b -> isHarshad(n, b))).boxed().toList();   // [1, 2, 4, 6]

4. Listing and Counting Harshad Numbers

About a third of the numbers up to 100 are Harshad numbers, and the share drops slowly as the numbers grow. A LongStream filter with the isHarshad() method lists and counts them for any range.

List<Long> upTo50 = LongStream.rangeClosed(1, 50).filter(n -> isHarshad(n)).boxed().toList();   // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42, 45, 48, 50]
long countTo100 = LongStream.rangeClosed(1, 100).filter(n -> isHarshad(n)).count();     // 33
long countTo1000 = LongStream.rangeClosed(1, 1_000).filter(n -> isHarshad(n)).count();  // 213

The numbers 1 to 10 form a run of ten consecutive Harshad numbers. No run longer than ten starts below 10,000,000, and it has been proven that no 21 consecutive integers can all be Harshad numbers in base 10.

5. A Lucky-Draw Rule for Receipt Numbers

Say a coffee chain runs a promotion in its app. A receipt whose number is a Harshad number wins a free drink, which makes about 7 percent of the 8-digit receipt numbers from 20,000,000 to 29,999,999 winners. Receipt numbers are long values from the billing system, and the rule must also be clear to the support team when a customer asks why a receipt did not win.

record DrawResult(long receipt, long digitSum, boolean wins) {}
static DrawResult luckyDraw(long receipt) {
    if (receipt <= 0) {
        throw new IllegalArgumentException("Invalid receipt number: " + receipt);
    }
    long digitSum = 0;
    for (long t = receipt; t > 0; t /= 10) {
        digitSum += t % 10;
    }
    return new DrawResult(receipt, digitSum, receipt % digitSum == 0);
}
DrawResult win = luckyDraw(20_250_304);     // DrawResult[receipt=20250304, digitSum=16, wins=true]
DrawResult lose = luckyDraw(20_250_311);    // DrawResult[receipt=20250311, digitSum=14, wins=false]
DrawResult bad = luckyDraw(0);              // IllegalArgumentException

The method returns the digit sum together with the decision, so the support screen can show “2 + 0 + 2 + 5 + 0 + 3 + 0 + 4 = 16” instead of a bare yes or no. An invalid receipt number fails with an exception, because a silent false would hide a bug in the billing data. More digit puzzles of this kind, such as the disarium number, are collected on the Java examples page.

6. Harshad Number FAQs

Quick checks on small numbers and on the two names cover most of what readers search for after the basic program works.

6.1. Is 0 a Harshad number?

No. The digit sum of 0 is 0, and division by 0 is undefined, so the definition covers positive integers only. In Java, 0 % 0 on int values throws ArithmeticException, which is why the safe methods return false for 0 first.

6.2. Are all single-digit numbers Harshad numbers?

Yes. A digit from 1 to 9 is its own digit sum, and every number divides itself. The number 10 is Harshad too, because its digit sum is 1.

6.3. What is the difference between a Harshad number and a Niven number?

There is none in base 10. Kaprekar used the name Harshad, and Niven number is the name used in many English texts. Both describe numbers divisible by their digit sum.

6.4. Are factorials Harshad numbers?

Most small ones are, but not all. Every factorial up to 431! is a Harshad number, and 432! is the first one that is not. A check with BigInteger and the digit characters of 432! confirms it.

6.5. Is 21 a Harshad number?

Yes. The digit sum is 2 + 1 = 3, and 21 = 3 x 7.

7. Conclusion

A Harshad number is divisible by the sum of its digits, such as 18, 156 and 1729. The check is a digit-sum loop plus one remainder test, and it must reject 0 and negative numbers before dividing, otherwise it throws ArithmeticException.

Changing 10 to another base gives n-Harshad numbers, and only 1, 2, 4 and 6 are Harshad in every base. Returning the digit sum with the result, as in the lucky-draw record, makes the rule simple to explain to the people who use it.

8. References

Happy Learning !!

Source Code on Github

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.