Program to Check if a Number is a Harshad Number in Java

Harshad Number

A Harshad number (also called a Niven number) is a number that is divisible by the sum of its digits. For example, 18 is a Harshad number because 1 + 8 = 9 and 18 is divisible by 9.

We will explore a method to check if a given number is a Harshad number using Java programming.

Method: Using a while Loop

We extract each digit, sum them up, and check if the original number is divisible by this sum.

import java.util.Scanner;

public class Main {
    public static boolean isHarshad(int num) {
        int originalNum = num, sum = 0, digit;
        
        // Calculate the sum of digits
        while (num > 0) {
            digit = num % 10;
            sum += digit;
            num /= 10;
        }
        
        return (originalNum % sum == 0);
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = scanner.nextInt();
        
        if (isHarshad(num))
            System.out.println(num + " is a Harshad number");
        else
            System.out.println(num + " is not a Harshad number");
        
        scanner.close();
    }
}
            

Output:

Enter a number: 18
18 is a Harshad number
Easy aceess next quctions
Getting Started

Positive or Negative number: C C++ Java Python

Even or Odd number: C C++ Java Python

Sum of First N Natural numbers: C C++ Java Python

Sum of N natural numbers: C C++ Java Python

Sum of numbers in a given range: C C++ Java Python

Greatest of two numbers: C C++ Java Python

Greatest of the Three numbers: C C++ Java Python

Leap year or not: C C++ Java Python

Prime number: C C++ Java Python

Prime number within a given range: C C++ Java Python

Sum of digits of a number: C C++ Java Python

Reverse of a number: C C++ Java Python

Palindrome number: C C++ Java Python

Armstrong number: C C++ Java Python

Armstrong number in a given range: C C++ Java Python

Harshad number: C C++ Java Python

Abundant number: C C++ Java Python

Friendly pair: C C++ Java Python