In recreational mathematics, a Harshad number (or Niven number) in a given number base, is an integer that is divisible by the sum of its digits when written in that base. Harshad numbers in base n are also known as n-Harshad (or n-Niven) numbers. Harshad numbers were defined by D. R. Kaprekar, a mathematician from India.

Java Code assuming base 10:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class HarshadNumber {
  public static void main(String[] args) {
    long seq = 100; //limit the seq of harshad numbers
    int num, sum;
    for (int i = 1; i <= seq; i++) {
      num = i;
      sum = 0;
      while (num != 0) {
        sum += num % 10;
        num = num / 10;
      }
      if (i % sum == 0) {
        System.out.println(i);
      }
    }
  }
}

Output: 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

Javascript Code assuming base 10:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var i,num,sum,temp,limit=100;
for(i=1;i<=limit;i++){
    num = i;
    sum = 0;
    temp = 0;
    while(num!=0){
        sum+=num%10;
        temp = num/10;
        //observe the use of toFixed and floor functions
        //They are necessary here to get the desired result
        // Example: var a = 5/10
        // a==0.5
        // a.toFixed() = "1"
        // Math.floor(a) = 0
        num=(Math.floor(temp)).toFixed();
    }
    if(i%sum == 0){
        console.log(i);
    }
}

Links:
The On-Line Encyclopedia of Integer Sequences: Harshad Number

“Without mathematics, there’s nothing you can do. Everything around you is mathematics. Everything around you is numbers.”
-Shakuntala Devi

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>