Last Updated: June 7, 2026
A Harshad number is the number itself divided evenly by the sum of its decimal digits. For 18, the digit sum is 1 + 8 = 9, and 18 % 9 is 0, so 18 passes. For 19, the digit sum is 1 + 9 = 10, and 19 % 10 is 9, which is not zero, so 19 fails.
The digit sum is always at least 1 for any positive number, since at least one digit is non-zero. That guarantees the divisibility check never divides by zero once a positive n reaches the test. Every single-digit positive number is automatically a Harshad number, because its digit sum equals the number itself, and any number divides itself evenly. That covers 1 through 9.
The case that needs an explicit guard is n being zero or negative. The definition restricts Harshad numbers to positive integers, so those inputs return false directly. Guarding them also avoids dividing by the digit sum of 0, which is 0, an undefined operation.
n can be a single-digit positive number → The digit sum equals n itself, so n % digitSum is 0 and the answer is true. Values 1 through 9 are always Harshad numbers.n can be 0 or negative → Only positive integers qualify, so return false before computing anything. This also avoids dividing by the digit sum of 0, which is 0 and undefined.n has a digit sum of at least 1 once positive → A positive number has a non-zero digit, so the divisor in n % digitSum is never zero for valid inputs.The definition translates into two steps: compute the digit sum, then check divisibility. Reading the digits one at a time is the standard % 10 and / 10 loop: n % 10 gives the last digit, and n / 10 removes it. Repeating until the number reaches 0 visits every digit exactly once, accumulating their sum.
The final test is a single modulo, n % digitSum == 0. That check needs the original n, so the digit extraction runs on a copy and leaves n intact. The guard for non-positive n runs first.
n is less than or equal to 0, return false.digitSum to 0 and copy n into a temporary variable temp.temp is greater than 0, add temp % 10 to digitSum, then set temp to temp / 10.true if n % digitSum is 0, and false otherwise.Input:
The value 18 is greater than 0, so the digit sum loop runs. temp starts at 18. The last digit is 18 % 10 = 8, so digitSum becomes 8, and temp becomes 18 / 10 = 1. The last digit is now 1 % 10 = 1, so digitSum becomes 9, and temp becomes 1 / 10 = 0. The loop stops because temp reached 0. The digit sum is 9, and 18 % 9 is 0, so the answer is true.
n. Since the digit count grows with the logarithm of the value, this is O(log n). The loop runs once per digit, and the final modulo is constant time.n.