Python BasicsEasy

Harshad number

Detailed guide and Python implementation for the 'Harshad number' problem.

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?
Consider using Basics-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

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

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.