Hardshad Numbers

Try me

Open In ColabBinder

Harshad numbers or Niven numbers are integer numbers which are divisible by the sum of its digits in a given base. For instance, 12 is a Harshad number in base 10 because it is divisible by (1 + 2) 3, and 20 is a Harshad number because it is divisible by (2 + 0) 2. However, 15 is not a Harshad number in base 10 because it is not divisible by (1+5) 6. In general, an integer number \(X\) can be expressed in a given base \(n\) as:

\[X = \sum_{i=0}^{m-1}{a_i*n^i}\]

where \(m\) is the number of digits and (\(a_0, a_1, a_2, ..., a_{m-1}\)) are the digits of the integer number. \(X\) is a Harshad number in base n if and only if:

\[X \mod \sum_{i=0}^{m-1}{a_i0} = 0\]

That is, the remainder after integer division of \(X\) by the sum of its digits is 0. You can read everything about Harshad numbers here.

Write a function that tests if an integer number passed as argument is a Harshad number in base 10 (that is, it returns True if the number can be divided by the sum of its digits). Can you modify the function so that it takes a second parameter with the base for which you want to make the test?