Harshad Number - Problem
Harshad Number (also known as Niven number) is a fascinating mathematical concept where a number is divisible by the sum of its own digits.

Given an integer x, determine if it's a Harshad number:
• If YES: return the sum of its digits
• If NO: return -1

Example:
12 → digits: 1, 2 → sum: 3 → 12 ÷ 3 = 4 ✓ → return 3
11 → digits: 1, 1 → sum: 2 → 11 ÷ 2 = 5.5 ✗ → return -1

Input & Output

example_1.py — Basic Harshad Number
$ Input: x = 12
Output: 3
💡 Note: 12 has digits 1 and 2. Sum = 1 + 2 = 3. Since 12 % 3 = 0, 12 is divisible by 3, so we return 3.
example_2.py — Non-Harshad Number
$ Input: x = 11
Output: -1
💡 Note: 11 has digits 1 and 1. Sum = 1 + 1 = 2. Since 11 % 2 = 1 ≠ 0, 11 is not divisible by 2, so we return -1.
example_3.py — Single Digit
$ Input: x = 5
Output: 5
💡 Note: 5 has only one digit: 5. Sum = 5. Since 5 % 5 = 0, 5 is divisible by itself, so we return 5. All single-digit numbers are Harshad numbers.

Constraints

  • 1 ≤ x ≤ 100
  • x is a positive integer
  • All single-digit numbers (1-9) are Harshad numbers

Visualization

Tap to expand
Harshad Number Algorithm VisualizationNumber144Input1Hundreds4Tens4OnesSum91 + 4 + 4 = 9144 ÷ 9= 16remainder 0Divisibility Check✓ HARSHAD NUMBERReturn: 9144 is divisible by sum of its digits!extractsumdivideresult
Understanding the Visualization
1
Digit Extraction
Break down the number into individual digits using modulo and division
2
Sum Calculation
Add all the extracted digits together
3
Divisibility Test
Check if original number divides evenly by the digit sum
Key Takeaway
🎯 Key Insight: A number is Harshad if it's divisible by the sum of its digits - we just need digit extraction and one modulo check!
Asked in
Google 15 Amazon 12 Adobe 8 Microsoft 6
28.4K Views
Medium Frequency
~8 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen