Harshad Number Program in Java with Examples

In this tutorial, I will be sharing what is a Harshad number, examples of Harshad number, algorithm, and java program to check whether a given number is a Harshad number or not. The Harshad number is also known as the Niven number.

Read Also: Automorphic Number in Java

What is Harshad Number

According to Wikipedia,

In mathematics, a Harshad number or Niven number is an integer (in base 10 or any given number base) that is divisible by the sum of its digits when written in that base.

Examples:

Number to check: 200  
Sum of digits: 2+0+0 = 2 
Is 200(Given number) divisible by 2(Sum of digits): Yes // 200 is a Harshad number
 
Number to check: 60  
Sum of digits: 6+0 = 6 
Is 60(Given number) divisible by 6(Sum of digits): Yes // 60 is a Harshad number 

Below are examples of numbers which are NOT Harshad numbers:

Number to check: 205  
Sum of digits: 2+0+5 = 7 
Is 205(Given number) divisible by 7(Sum of digits): No // 205 is NOT a Harshad number
 
Number to check: 85  
Sum of digits: 8+5 = 13 
Is 85(Given number) divisible by 13(Sum of digits): No // 85 is NOT a Harshad number

List of Harshad numbers from 1 to 50 are:   1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42, 45, 48, 50


Harshad Number in Java


Read Also: Ugly Number in Java

Java Program for Harshad Number

import java.util.*;
public class JavaHungry
{
public static void main(String args[]) {
System.out.println("Enter any number : ");
Scanner scan = new Scanner(System.in);
Integer inputNumber = scan.nextInt();
checkHarshadNumber(inputNumber);
}

public static void checkHarshadNumber(int inputNumber)
{
int sumOfDigits = 0;
int number = inputNumber;
while(number > 0)
{
int remainder = number % 10;
sumOfDigits = sumOfDigits + remainder;
number = number/10;
}
if(inputNumber % sumOfDigits == 0)
System.out.println(inputNumber +" is a Harshad Number");
else
System.out.println(inputNumber + " is NOT a Harshad Number");
}
}

Output:
Enter any number :
11 is NOT a Harshad Number
 

Algorithm For Harshad Number

1. Calculate the sum of digits of the inputNumber.
2. If inputNumber is divisible by sumOfDigits then the inputNumber is Harshad number otherwise not.

That's all for today, please mention in comments in case you have any questions related to Harshad number program in java with examples.

You may also like:

Bouncy number program in Java (answer)
Special number program in Java (solution)
Perfect number program in Java (solution)
Pronic number program in Java (answer)
Happy number program in Java (answer)
Duck number program in Java (answer)
Magic number program in Java (solution)
Neon number program in Java (solution)
Disarium number program in Java (answer)

0 Comments