Harshad Number

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

JavaIntermediate
Java
import java.util.Scanner;

public class Main {
    private static int sumOfDigits(int n) {
        n = Math.abs(n);
        int sum = 0;
        while (n != 0) {
            sum += n % 10;
            n /= 10;
        }
        return sum;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int n = sc.nextInt();

        int sum = sumOfDigits(n);
        if (sum != 0 && n % sum == 0) {
            System.out.println(n + " is a Harshad Number");
        } else {
            System.out.println(n + " is not a Harshad Number");
        }
        sc.close();
    }
}

Output

Enter a number: 18
18 is a Harshad Number

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