Table of Contents
Show you some examples
Example
Instance-3
grammar" >grammar
algorithm
Algorithm 2
Multiple methods" >Multiple methods
Method 1: Not using strings
Output
Method 2: Using strings
Home Java javaTutorial How to check if a number is Harshad number in Java?

How to check if a number is Harshad number in Java?

Sep 24, 2023 pm 09:01 PM
java number examine harshad number

How to check if a number is Harshad number in Java?

Harshad number is divisible by the sum of its digits. Simply put, if the sum of all the digits of a number is a factor of that number, then it is a Harshad number.

In this article, we will see how to check Harshad number using Java programming language.

Show you some examples

Example 1

Enter the number as 18

Let us check it using the logic of Harshad number −

The sum of the digits of the number = 1 8 = 9.

So, 18 is divisible by 9.

Therefore, 18 is a Harshad number.

Instance-2

is translated as:

Instance-2

The number entered is 3

Let us check it using the logic of Harshad number −

The sum of the digits of the number = 3.

So, 3 can be divided by 3.

Therefore, 3 is the Harshad number.

The Chinese translation of

Instance-3

is:

Instance-3

Enter the number as 15

Let us check it using the logic of Harshad number −

The sum of the digits of the number = 1 5 = 6.

So, 15 is not divisible by 6.

Therefore, 14 is not a Harshad number.

Some other examples of Harshad numbers include 1, 2, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, etc.

grammar

Convert an integer value to a string value using the built-in toString() method.

The following is the syntax to convert an integer value to a string value, then find its length and assign the length to an integer variable to get the total number of digits in the number -

String str = Integer.toString(input_number);
Copy after login

To get the length of an integer, we will use the built-in length() method of the Java String class Method returns the length of the String object.

int length = st.length();
Copy after login

To get the character at a specific position/index in a string, we use the charAt() method. Where charAt(i)-‘0’ returns the actual integer value.

int num = st.charAt(i)-‘0’;
Copy after login

Where "st" refers to the string, "i" is the iterator variable that iterates over the string.

algorithm

Algorithm 1

  • Step 1 - Get an integer via initialization or user input.

  • Step 2 - Find the sum of each digit of the number by iterating through each digit of the number.

  • Step 3 - Then check if the original number is divisible by the sum of all digits of the number. The given number is a Harshad number if it is divisible, otherwise it is not a Harshad number

Algorithm 2

  • Step 1 - Get an integer via initialization or user input.

  • Step 2 - Convert the integer to a string using the built-in toString() method.

  • Step 3 - Find the length of the string by using the built-in length() method.

  • Step 4 - Then by using a for loop, iterate until the length of the string and get an integer value 0' from the string using charAt(i)-' And record the sum of all numbers.

  • Step 5 - Then check if the original number is divisible by the sum of all digits of that number. The given number is a Harshad number if it is divisible, otherwise it is not a Harshad number.

Multiple methods

We provide solutions in different ways

  • Do not use strings

  • By using strings

Let’s look at the program and its output one by one.

Method 1: Not using strings

In this method, an integer value will be initialized in the program, and then by using Algorithm-1 we can check whether a number is a Harshad number.

Example

public class Main{
   //main method
   public static void main(String args[]){

      //Declared an integer variable and initialized a number as value
      int originalNumber = 21;

      //printing the given number to be checked
      System.out.println("Given number: "+originalNumber);

      //keep a copy of original number
      int copyOfOriginalNumber = originalNumber;

      //initialize sum as 0
      int sum = 0;

      //Find sum of all digits of the number
      //continue the loop till the number is greater than 0
      while(originalNumber > 0){

         //get the rightmost digit of the number by using % operator
         int rem = originalNumber%10;

         //add the digit(rem) to sum
         sum = sum + rem;

         //remove the rightmost digit from number and get the updated number
         originalNumber = originalNumber/10;
      }

      //printing the result
      if(copyOfOriginalNumber % sum == 0)
         System.out.println(copyOfOriginalNumber+" is a Harshadnumber");
      else
         System.out.println(copyOfOriginalNumber+" is not a Harshadnumber");
   }
}
Copy after login

Output

Given number: 21
21 is a Harshad number
Copy after login

Method 2: Using strings

In this method, an integer value will be initialized in the program and then using Algorithm-2 we will check whether the number is a Harshad number or not.

Example

public class Main{
   //main method
   public static void main(String args[]){

      //Declared an integer variable and initialized a number as value
      int originalNumber = 40;

      //printing the given number to be checked
      System.out.println("Given number: "+originalNumber);

      //keep a copy of original number
      int copyOfOriginalNumber = originalNumber;

      //initialize sum as 0
      int sum = 0;

      //convert the integer to string by using toString() method
      String str = Integer.toString(originalNumber);
       
      //find length of String by using length() method
      //which is nothing but total number of digits in the given number
      int length=str.length();
       
      //iterate the String and get the digits by using charAt(i)-'0'
      //find the sum of digits
      for(int i = 0; i < length; i++){
         sum += str.charAt(i)-'0';
      }

      //printing the result 
      if(copyOfOriginalNumber % sum == 0)
         System.out.println(copyOfOriginalNumber+" is a Harshad number");
      else
         System.out.println(copyOfOriginalNumber+" is not a Harshad number");      
   }
}
Copy after login

Output

Given number: 40
40 is a Harshad number
Copy after login

In this article, we explored how to check if a number is a Harshad number in Java using different methods.

The above is the detailed content of How to check if a number is Harshad number in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

See all articles