Harshad Numbers

Sat, 04 Mar 2017 01:14:27 -0600

Today while looking up something in my productivity nemesis Wikipedia, I was waylaid by an article on Harshad numbers. (Link goes to Wolfram Mathworld out of spite.) This was interesting to me because Harshad is my patronym. Harshad numbers are also known as Niven numbers but what kind of a crazy name is that? A Harshad number is a positive integer that is divisible by the sum of its' digits.

1-10 are obviously Harshad numbers in base 10. 11 is not because 1 + 1 = 2 and 11 is not divisible by 2. 12 is because 1 + 2 = 3 and 12 is divisible by 3. And so on...you get the picture. Things get even more interesting when you deal with other bases.

Here is a perl one-liner to get the base 10 Harshad numbers from 1 to 100.

$ perl -E '$i=0+shift;for$n(1..$i){$t=0;map{ $t+=$_+0}(split q{},$n);print $n%$t==0?"$n ":q{};}say' 100
1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 45 48 50 54 60 63 70 72 80 81 84 90 100