Check Harshad Number in Java

What you’ll learn

  • Harshad rule: n % digitSum(n) == 0 for positive numbers.
  • Single-number check and range listing in Java.
  • How to avoid division-by-zero edge cases.

Prerequisites

  • Basic Java syntax, loops, conditionals, and methods.
  • Comfort with integer arithmetic and console input/output.

Math definition

This problem is driven by a deterministic numeric rule: for each valid input, apply the same formula repeatedly and classify the result.

Intuition with examples

Work a small input by hand first, then map each step to one Java loop iteration. This makes the control flow and stopping condition clear.

Live preview

Live result
Press "Check Harshad".

Algorithm

Goal: decide whether n is divisible by the sum of its digits.

Compute digit sum

Use a loop with % 10 and / 10 to build sum.

Apply divisibility check

Return false for n <= 0 or sum == 0; otherwise test n % sum == 0.

📜 Pseudocode

Pseudocode
function isHarshad(n):
    if n <= 0: return false
    sum = digitSum(n)
    if sum == 0: return false
    return (n mod sum) == 0
1

Single value: 18

java
public class Main {
    static int digitSumPositive(int n) {
        int sum = 0;
        while (n > 0) {
            sum += n % 10;
            n /= 10;
        }
        return sum;
    }

    static boolean isHarshad(int number) {
        if (number <= 0) return false;
        int sum = digitSumPositive(number);
        return sum != 0 && number % sum == 0;
    }

    public static void main(String[] args) {
        int number = 18;
        if (isHarshad(number)) {
            System.out.println(number + " is a Harshad number.");
        } else {
            System.out.println(number + " is not a Harshad number.");
        }
    }
}
📤 Output
18 is a Harshad number.
2

Harshad numbers in [1, 20]

java
public class Main {
    static int digitSumPositive(int n) {
        int sum = 0;
        while (n > 0) {
            sum += n % 10;
            n /= 10;
        }
        return sum;
    }

    static boolean isHarshad(int num) {
        if (num <= 0) return false;
        int sum = digitSumPositive(num);
        return sum != 0 && num % sum == 0;
    }

    public static void main(String[] args) {
        System.out.println("Harshad numbers in the range 1 to 20:");
        for (int i = 1; i <= 20; i++) {
            if (isHarshad(i)) System.out.print(i + " ");
        }
        System.out.println();
    }
}
📤 Output
Harshad numbers in the range 1 to 20:
1 2 3 4 5 6 7 8 9 10 12 18 20

Optimization notes

Keep it simple. Prefer clear loops and method extraction before micro-optimizations.

Reuse computed values. Avoid recomputing the same sub-result inside nested loops.

❓ FAQ

A positive integer n is Harshad if n is divisible by the sum of its decimal digits.
Yes. Its digit sum is 1, and 1 is divisible by 1.
Because n % 0 is invalid. In this topic we use only positive integers, so sum is naturally positive.
Yes. Use digits in base b and apply the same divisibility rule.
O(log10 n) digit operations to compute digit sum, then one modulus.
Not exactly. Harshad uses one digit-sum divisibility test, not repeated reduction to one digit.

🔄 Input / output examples

Use the sample programs as reference: provide valid numeric input and verify the output pattern matches the problem definition.

Edge cases

Bounds

Smallest valid input

Confirm behavior for minimum accepted values.

Validation

Invalid input

Guard against non-numeric or out-of-range values when input is user-provided.

⏱️ Time and space complexity

TaskTimeExtra space
One number checkO(log n) digitsO(1)
Scan range [1, N]O(N log N)O(1)

Summary

  • Use a direct Java implementation of the numeric rule.
  • Validate input and test boundary cases.
  • Discuss complexity clearly in interviews.
Did you know?

Harshad numbers are also called Niven numbers. In base 10, a positive integer n is Harshad if n is divisible by the sum of its digits.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful