Harshad Number
Check whether a number is a Harshad (Niven) number (divisible by sum of its digits).
IntermediateTopic: Module 3: Loop Programs
Java Harshad Number Program
This program helps you to learn the fundamental structure and syntax of Java programming.
import java.util.Scanner;
public class Main {
private static int sumOfDigits(int n) {
n = Math.abs(n);
int sum = 0;
while (n != 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
int sum = sumOfDigits(n);
if (sum != 0 && n % sum == 0) {
System.out.println(n + " is a Harshad Number");
} else {
System.out.println(n + " is not a Harshad Number");
}
sc.close();
}
}Output
Enter a number: 18 18 is a Harshad Number
Understanding Harshad Number
We compute sum of digits and check if the number is divisible by this sum.
Note: To write and run Java programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Java Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Java programs.