Placement Prep

Harshad Number (Niven Number): Algorithm, Programs in Python, Java, C

Learn what a Harshad number (Niven number) is, see worked examples, and get programs in Python, Java, and C to check any integer.

By FACE Prep Team 5 min read
harshad-number niven-number number-theory python-programs java-programs digit-sum placement-prep

A Harshad number is any positive integer divisible by the sum of its own digits.

What Is a Harshad Number?

The term comes from Sanskrit: harsha (joy) + da (gives), meaning roughly “joy-giver.” Indian mathematician D. R. Kaprekar coined the name in the 1950s. The same property was studied independently by mathematician Ivan Niven, which is why the Wikipedia article on Harshad numbers lists “Niven number” as an equally valid alternative name.

The defining test is simple. Take any positive integer. Sum its digits. If the original number divides evenly by that digit sum, it is a Harshad number. If not, it is not.

Worked Examples

The table below verifies six numbers from first principles:

NumberDigit sumDivision checkVerdict
181 + 8 = 918 / 9 = 2Harshad
212 + 1 = 321 / 3 = 7Harshad
17291 + 7 + 2 + 9 = 191729 / 19 = 91Harshad
191 + 9 = 1019 / 10 = 1.9Not Harshad
1001 + 0 + 0 = 1100 / 1 = 100Harshad
131 + 3 = 413 / 4 = 3.25Not Harshad

The number 1729 is a particularly clean demonstration: digit sum 19, and 19 times 91 equals 1729 exactly. It also happens to be the Hardy-Ramanujan number (the smallest positive integer expressible as the sum of two cubes in two different ways), but that is a separate property entirely. The full sequence of Harshad numbers, maintained at OEIS A005349, begins: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30…

Edge Cases Worth Knowing

Three cases that trip up first-time implementations:

  • Zero: The digit sum of 0 is 0. Division by zero is undefined, so 0 is not a Harshad number. Add a guard: if s == 0, return “Not Harshad Number” before the modulo check.
  • Single digits 1 through 9: Each is its own digit sum, so each divides evenly by itself. All nine are Harshad numbers.
  • Negative inputs: The standard definition applies to positive integers only. If the problem allows negative input, pass the absolute value to the digit-sum function.

Algorithm

The logic fits in four steps:

  • Step 1: Read the input integer n.
  • Step 2: Extract each digit and compute their sum s (via modulo and integer division, or by converting to a string).
  • Step 3: If s equals 0, output “Not Harshad Number” and stop.
  • Step 4: If n % s == 0, output “Harshad Number”; otherwise output “Not Harshad Number”.

The algorithm runs in O(log n) time: one loop iteration per digit, with the digit count growing as the base-10 logarithm of n. Space complexity is O(1), since no data structure scales with the input. For a broader treatment of why logarithmic loops produce this complexity class, see space complexity of algorithms with examples.

Programs to Check a Harshad Number

Python

def digit_sum(n):
    return sum(int(d) for d in str(n))

def is_harshad(n):
    s = digit_sum(n)
    return s != 0 and n % s == 0

n = int(input("Enter a number: "))
print("Harshad Number" if is_harshad(n) else "Not Harshad Number")

Sample run:

  • Input: 18
  • Output: Harshad Number

The digit_sum function converts the integer to a string, iterates over each character, and accumulates integer values. This produces the same result as the modulo-loop approach shown in Java below, but reads more naturally in Python. The standalone digit-sum problem appears across number-property checks of all kinds; the dedicated treatment is at program to find the sum of digits of a given number.

Java

import java.util.Scanner;

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

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int s = digitSum(n);
        System.out.println((s != 0 && n % s == 0) ? "Harshad Number" : "Not Harshad Number");
    }
}

The modulo-loop extracts one digit per iteration from the least-significant end. No string conversion, no extra library. The s != 0 guard before the modulo prevents a division-by-zero on an input of 0.

C

#include <stdio.h>

int digitSum(int n) {
    int sum = 0;
    while (n > 0) {
        sum += n % 10;
        n /= 10;
    }
    return sum;
}

int main() {
    int n;
    scanf("%d", &n);
    int s = digitSum(n);
    printf("%s\n", (s != 0 && n % s == 0) ? "Harshad Number" : "Not Harshad Number");
    return 0;
}

The C version mirrors the Java logic exactly. Keep the s != 0 guard before the modulo to avoid undefined behaviour on a zero digit sum.

Finding Harshad Numbers in a Range

Placement coding rounds often ask for all Harshad numbers between two given integers, rather than checking a single value. Add an outer loop:

Python — Range Variant

def digit_sum(n):
    return sum(int(d) for d in str(n))

def harshad_in_range(low, high):
    return [n for n in range(low, high + 1)
            if digit_sum(n) != 0 and n % digit_sum(n) == 0]

low, high = map(int, input("Enter range (low high): ").split())
print(harshad_in_range(low, high))

For the input range 1 to 30, this returns:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30]

The range variant preserves the same O(log n) check per element; total complexity across a range of k elements is O(k log max). For a related problem that combines range iteration with a divisibility condition, see finding the number of integers with exactly 9 divisors in a given range.

Placement Context

Number-property questions (Harshad, Armstrong, palindrome, strong number, perfect number) are a consistent fixture in campus placement coding rounds. The typical problem gives a single integer and asks for classification; harder variants give a range and ask you to count or list qualifying integers.

The important habit is separating the reusable helper (digit sum, here) from the property check. A clean digit_sum function that handles the zero-guard can be pasted unchanged into Armstrong-number, digital-root, and Harshad checks without modification. That reusability is what evaluators notice when they read student code under test conditions.

Once you are comfortable with the digit-sum pattern across multiple number properties, the next step is practising under time pressure with real test constraints.

Writing the digit-sum loop fluently in Python is the same basic iteration skill used when scripting LLM output parsing. If you want to see how Python moves from digit manipulation into actual model calls and prompt pipelines, TinkerLLM is the sandbox to try next. The entry point is ₹299.

Primary sources

Frequently asked questions

Is 1729 a Harshad number?

Yes. The digit sum of 1729 is 1+7+2+9 = 19, and 1729 divided by 19 equals 91 exactly, so 1729 qualifies as a Harshad number.

What is the difference between a Harshad number and an Armstrong number?

An Armstrong number equals the sum of each digit raised to the power of the total digit count (e.g., 153 = 1 cubed + 5 cubed + 3 cubed). A Harshad number is simply divisible by its digit sum, which is a much looser condition. All single-digit integers 1 through 9 satisfy both definitions.

Is 0 a Harshad number?

No. The digit sum of 0 is 0, and dividing by zero is undefined, so 0 is excluded from the Harshad sequence by convention.

Are Harshad numbers tested in placement exams?

Yes. They appear in TCS NQT, Wipro NLTH, and CoCubes coding rounds as number-property identification MCQs and short coding problems alongside Armstrong, palindrome, and strong number questions.

What is the time complexity of checking a Harshad number?

O(log n) time — the digit-extraction loop runs once per digit, and the digit count grows as the base-10 logarithm of n. Space complexity is O(1) since no extra data structure grows with input size.

Build AI projects

A self-paced playground for building with LLMs.

TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.

Try TinkerLLM (₹299 launch)
Free AI Roadmap PDF