# Java Program to Check Harshad number

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 –

1. Calculate the sum of each digit present in number.
2. 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) {

}

{
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

```

Happy Learning !!

Ref : Wikipedia

Subscribe
Notify of
Inline Feedbacks

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.