Harshad Number in Java

Write a program that will allow the user to enter a positive integer. Test whether the number is a Harshad Number or not.

If the number is divisible by the sum of its digits, then it is a Harshad Number.

Use a recursive function int sumOfDigits(num) to compute and return the sum of the digits.

Program:

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

Leave a Reply