Back to Practice Dashboard
Python BasicsEasy

Harshad number

Learn how to solve the 'Harshad number' problem. This detailed resource details brute force and optimized approaches.

Problem Statement

Easy

Write a function is_harshad(n) that takes a positive integer n and returns True if n is a Harshad (Niven) number, or False otherwise. A Harshad number is a number 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.

Constraints
  • 1 <= n <= 10^9

Examples

Example 1
Input
n = 18
Output
True
Explanation

Sum of digits = 1 + 8 = 9. Since 18 % 9 == 0, it is a Harshad number.

Example 2
Input
n = 21
Output
True
Explanation

Sum of digits = 2 + 1 = 3. Since 21 % 3 == 0, it is a Harshad number.

Example 3
Input
n = 14
Output
False
Explanation

Sum of digits = 1 + 4 = 5. Since 14 % 5 != 0, it is not a Harshad number.

Need a Hint?
Use simple arithmetic operators (like modulo `%`, division `//`), conditional checks, or loops to inspect number properties.
Edge Cases to Watch
  • Empty list or null input variables
  • Single item lists/arrays
  • Extremely large input bounds causing integer or stack overflow

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor