Java Program to Check Harshad number

1. what is a harshad number


A number is called a harshad number (or niven number) is an integer that is divisible by the sum of its digits. i.e. A number MN is divisible by (M+N).

For example, consider following example of number 40.

Given number is : 40

Sum of digits : 4 + 0 = 4

Is 40 divisible by 4? Yes. So 40 is harshad number.

A number which is a harshad number in every number base is called an all-harshad number, or an all-Niven number. There are only four all-harshad numbers: 1, 2, 4, and 6.


2. Algorithm to determine harshad number

To find if a given number is harshad or not –

  1. Calculate the sum of each digit present in number.
  2. Divide the number with sum of digits. If number is divisible with remainder zero, the number i harshad number; else not.

3. Java Program to find harshad number

Main.java
public class Main
{
    public static void main(String[] args) {
         
        System.out.println("20 is harshad number " + isHarshadNumber(20));
        System.out.println("12 is harshad number " + isHarshadNumber(12));
        System.out.println("42 is harshad number " + isHarshadNumber(42));
         
        System.out.println("13 is harshad number " + isHarshadNumber(13));
        System.out.println("19 is harshad number " + isHarshadNumber(19));
        System.out.println("25 is harshad number " + isHarshadNumber(25));
    }
     
    static boolean isHarshadNumber(int numberToCheck)
    {
        int temp = numberToCheck;
        int sumOfDigits = 0;
        while (temp > 0) {
          long rem = temp % 10;
          sumOfDigits += rem;
          temp = temp / 10;
        }
         
        return numberToCheck % sumOfDigits == 0 ? true : false;
    }


Program output.

Console
20 is harshad number true
12 is harshad number true
42 is harshad number true
 
13 is harshad number false
19 is harshad number false
25 is harshad number false


Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Learn More

Java Programming Masterclass for Software Developers

Selenium WebDriver with Java -Basics to Advanced+Frameworks

Java In-Depth: Become a Complete Java Engineer!

JSP, Servlets and JDBC for Beginners: Build a Database App

JSP, Servlet, JSLT + Hibernate: A complete guide

The Complete ASP.NET MVC 5 Course

Build a Real-world App with ASP.NET Core and Angular 2 (4+)

Build an app with ASPNET Core and Angular from scratch

Announcing .NET Core 3.0 Preview 5

.NET Core 3.0 Preview Now Available!

Develop a basic website with .NET CORE 3.0 and pure JavaScript

Top 10 Testing Frameworks and Libraries for Java Developers

Java Tutorial For Beginners - Learn Java Programming - Part 1/5

50+ Java Interview Questions for Programmers

Originally published on https://howtodoinjava.com

#java

Java Program to Check Harshad number
1 Likes8.45 GEEK