# How to find if a number is Niven (Harshad number) or not in Java

In this tutorial, we’ll be finding out if a number is Niven number ( Harshad number ) or not in Java.

## Niven Number

Niven number or Harshad number is a number, perfectly divisible by the sum of its individual digits.

All single digit numbers are Niven numbers.

For Example:

1 -> Niven Number

18 -> Niven Number

20 -> Not Niven Number

Below is a representation of Niven numbers:

In the example given above, we can notice that 15/(1+5) = 2.5 ( i.e ) not perfectly divisible.

Therefore 15 is not a Niven number.

## Code for Finding if a number is Niven or not in Java

import java.util.*; class Niven { public static void main(String[]args) { Scanner scan = new Scanner(System.in); System.out.print("Enter the number: "); int number = scan.nextInt(); int total = 0; for(int k = number ; k > 0 ; k = k/10) { total = total + (k%10); } if(number%total == 0) { System.out.println("Harshad number"); } else { System.out.println("Not a Harshad number"); } } }

#### Explanation

- For each iteration, the last digit of the number is added to the “total” variable by the % operation which yields the remainder.
- The last digit is removed from the number using the / operation which yields the quotient.
- Check divisibility.

**Output:**

Hence we can find out if the given number is a Niven number or not.

If any questions please feel free to drop in your comments ðŸ™‚

You may also read:

You can also check out my other posts at:

https://codespeedy.com/author/k_preetham/

## Leave a Reply