Java Interview Program - Check Whether a Number is a Harshad (Niven) Number

Check Whether a Number is a Harshad (Niven) Number

A Harshad number (also known as a Niven number) is an integer that is divisible by the sum of its digits. For example, 18 is a Harshad number because 1 + 8 = 9, and 18 is divisible by 9.

This program helps us check whether a given number satisfies that condition. We will use basic arithmetic and loop constructs to solve this.

Examples

Example 1:

Input: 18  
Sum of digits: 1 + 8 = 9  
18 % 9 == 0 → Yes, Harshad number  
Output: true

Example 2:

Input: 21  
Sum of digits: 2 + 1 = 3  
21 % 3 == 0 → Yes, Harshad number  
Output: true

Example 3 (Edge Case):

Input: 13  
Sum of digits: 1 + 3 = 4  
13 % 4 != 0 → No, not a Harshad number  
Output: false

Interviewer Expectations

The interviewer wants to test your ability to:

  • Use arithmetic operations effectively
  • Extract digits from a number using loops
  • Write clean and logical conditions
  • Possibly explain time complexity and dry run logic

Approach

Here's how we solve this problem step by step:

  1. Take the input number
  2. Extract each digit and calculate the sum of digits
  3. Check if the original number is divisible by this sum

Dry Run Example (Input: 18)

  • Number = 18
  • Sum of digits = 1 + 8 = 9
  • 18 % 9 == 0 → It is divisible
  • Result: Harshad number

Java Program

public class HarshadNumberCheck {
    public static void main(String[] args) {
        int number = 18;
        int temp = number;
        int sumOfDigits = 0;

        while (temp != 0) {
            int digit = temp % 10;
            sumOfDigits += digit;
            temp /= 10;
        }

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

Possible Followup Questions with Answers

Q1: Can we check Harshad number for negative values?

By definition, Harshad numbers are positive integers. So typically, negative numbers are not considered.

Q2: How to check if a number is a Harshad number in any base?

You’d have to extract digits in that base using number % base and number / base.

Q3: Can we write a function to make it reusable?

public static boolean isHarshad(int number) {
    int temp = number, sum = 0;
    while (temp != 0) {
        sum += temp % 10;
        temp /= 10;
    }
    return number % sum == 0;
}

Q4: What is the time complexity?

O(log10n) because we extract digits one by one.


Comments

💬 Please keep your comment relevant and respectful. Avoid spamming, offensive language, or posting promotional/backlink content.
All comments are subject to moderation before being published.


Loading comments...