Harshad Number or Niven Number in Java

Harshad numbers are those integers which are divisible by the sum of the digits of the number.

Harshad numbers were defined by a mathematician from India, D. R. Kaprekar. Harshad numbers are also called Niven numbers.

For example, the number 198.

Sum of the digits of the number, 198 => 1 + 9 + 8 = 18, and, 18 * 11 = 198.

Hence, the number 198 is a Harshad number.

Below is a program that inputs a number, and checks whether it is a Harshad number or not.

Java Program to Check Harshad Number

import java.util.Scanner;

public class AutomorphicNumber
{
    static boolean isDivisible(int number, int divisor)
    {
        double quotient = (double) number / divisor;
        if (quotient == (int)quotient)
            return true;
        else
            return false;
    }
    static void checkForHarshad(int number)
    {
        int savedNumber = number;
        int sumOfDigits = 0;
        while(number != 0)
        {
            sumOfDigits += number % 10;
            number /= 10;
        }
        if( isDivisible(savedNumber, sumOfDigits) )
            System.out.println("The number is a Harshad number");
        else
            System.out.println("The number is not a Harshad number");
    }
    public static void main (String[] args)
    {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a Number: ");
        int number = input.nextInt();
        checkForHarshad(number);
    }
}

The program runs on the following algorithm to check whether a number is Harshad or not.

  1. Calculate the sum of the digits of the number.
  2. Check the divisibility of the number by the sum of the digits of the number by checking if the number when divided by the sum of the digits returns an integer.

Leave a Comment

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