What is a Harshad Number or Niven Number
Any positive integer which is divisible by the sum of its digits is a Harshad Number or Niven Number.
Let us see a few examples where we will determine whether the given number is a Harshad Number or not.
|Number||Sum of digits||Is Harshad Number?|
|2||2||Yes.(2 is divisible by 2)|
|16||7(6+1)||No.(16 is not divisible by 7)|
|102||3(1+0+2)||Yes.(102 is divisible by 3)|
|152||8(1+5+2)||Yes.(152 is divisible by 8)|
|200||2(2+0+0)||Yes.(200 is divisible by 2)|
Having understood what a Harshad (or Niven) Number is, let us now see how to implement a program in Java which checks whether the given number is a Harshad Number.
Java program to check if a number is a Harshad(or Niven) Number
main()method contains the entire logic for Harshad or Niven number determination.
- First the number to be tested is input using a
Scannerinstance which is initialized with
- The number is input using
Scanner.nextLong()method which reads the input as a
longvalue, and assigns it to a variable named
- The next section of the code calculates the sum of the digits of
- Value of
inputNois stored in a temporary variable named
tempis repeatedly divided by
10(base for decimal numbers) in a while loop till it becomes
0(i.e. when there are no digits remaining in the number). With each iteration of the while loop, the last digit is obtained as remainder on dividing
10. This remainder is added to the variable
sumOfDigitswhich, as its name suggests, stores the sum of individual digits of
- In the last section of the code, check for Harshad number is performed by dividing the
sumOfDigits. If the remainder is
inputNois a Harshad or Niven Number, else it is not.