Harshad Number in Java

Check whether a number is a Harshad (Niven) number (divisible by sum of its digits).

IntermediateModule 3: Loop ProgramsExample 24 of 25
harshad-number.java
1import java.util.Scanner;
2
3public class Main {
4 private static int sumOfDigits(int n) {
5 n = Math.abs(n);
6 int sum = 0;
7 while (n != 0) {
8 sum += n % 10;
9 n /= 10;
10 }
11 return sum;
12 }
13
14 public static void main(String[] args) {
15 Scanner sc = new Scanner(System.in);
16 System.out.print("Enter a number: ");
17 int n = sc.nextInt();
18
19 int sum = sumOfDigits(n);
20 if (sum != 0 && n % sum == 0) {
21 System.out.println(n + " is a Harshad Number");
22 } else {
23 System.out.println(n + " is not a Harshad Number");
24 }
25 sc.close();
26 }
27}

Output

Enter a number: 18
18 is a Harshad Number

What's going on

We compute sum of digits and check if the number is divisible by this sum.