Multiple Harshad Number in Java

A Multiple Harshad number is an integer which when divided by the sum of its digits, produces another Harshad number.

For example, consider the number 6804.
6 + 8 + 0 + 4 = 18.
6804 / 18 = 378
3 + 7 + 8 = 18
1 + 8 = 9.
18 / 9 = 2.
So, 6804 is a Multiple Harshad number.

A Harshad number is an integer which is divisible by the sum of its digits. It is also known as a Niven number.

For example, 18 is a Harshad number, because 1 + 8 = 9, which divides 18.

Write a program in Java to enter a number and check if it is a Multiple Harshad number.

import java.io.*;
class MultipleHarshad{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter the number: ");
        int n = Integer.parseInt(br.readLine());
        int s = sumOfDigits(n);
        if(n % s == 0){
            int num = n / s;
            int sum = sumOfDigits(num);
            if(num % sum == 0)
                System.out.println(n + " is a Multiple Harshad number.");
            else
                System.out.println(n + " is not a Multiple Harshad number.");
        }
        else
            System.out.println(n + " is not a Multiple Harshad number.");
    }
    public static int sumOfDigits(int n){
        int sum = 0;
        for(int i = n; i != 0; i /= 10)
            sum += i % 10;
        return sum;
    }
}

Leave a Reply