Learn to write a simple java program to verify if a given number is **harshad number** or not.

## 1. what is a harshad number

A number is called a **harshad number** (or **niven number**) is an integer that is divisible by the sum of its digits. i.e. **A number MN is divisible by (M+N)**.

For example, consider following example of number 40.

Given number is : 40

Sum of digits : 4 + 0 = 4

Is 40 divisible by 4? Yes. So 40 is harshad number.

A number which is a harshad number in every number base is called an

**all-harshad number**, or an**all-Niven number**. There are only four all-harshad numbers: 1, 2, 4, and 6.## 2. Algorithm to determine harshad number

To find if a given number is harshad or not –

- Calculate the sum of each digit present in number.
- Divide the number with sum of digits. If number is divisible with remainder zero, the number i harshad number; else not.

## 3. Java Program to find harshad number

public class Main { public static void main(String[] args) { System.out.println("20 is harshad number " + isHarshadNumber(20)); System.out.println("12 is harshad number " + isHarshadNumber(12)); System.out.println("42 is harshad number " + isHarshadNumber(42)); System.out.println("13 is harshad number " + isHarshadNumber(13)); System.out.println("19 is harshad number " + isHarshadNumber(19)); System.out.println("25 is harshad number " + isHarshadNumber(25)); } static boolean isHarshadNumber(int numberToCheck) { int temp = numberToCheck; int sumOfDigits = 0; while (temp > 0) { long rem = temp % 10; sumOfDigits += rem; temp = temp / 10; } return numberToCheck % sumOfDigits == 0 ? true : false; } }

Program output.

20 is harshad number true 12 is harshad number true 42 is harshad number true 13 is harshad number false 19 is harshad number false 25 is harshad number false

Happy Learning !!

Ref : Wikipedia