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
• If YES: return the sum of its digits
• If NO: return
Example:
•
•
Given an integer
x, determine if it's a Harshad number:• If YES: return the sum of its digits
• If NO: return
-1Example:
•
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
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!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code