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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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

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

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

What are the platforms for virtual currency trading around the world? The top ten latest 2025 digital currency app rankings What are the platforms for virtual currency trading around the world? The top ten latest 2025 digital currency app rankings Feb 27, 2025 pm 06:09 PM

The top four global virtual currency trading platforms in 2025 are: Binance: a leader in the industry, providing diversified trading options and innovative products. OKX: A huge user base, providing comprehensive cryptocurrency services. Gate.io: User-friendly, offering a wide range of cryptocurrency options. Bitget: Focus on derivatives trading and provides high leverage futures contracts.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

Java Made Simple: A Beginner's Guide to Programming Power Java Made Simple: A Beginner's Guide to Programming Power Oct 11, 2024 pm 06:30 PM

Java Made Simple: A Beginner's Guide to Programming Power Introduction Java is a powerful programming language used in everything from mobile applications to enterprise-level systems. For beginners, Java's syntax is simple and easy to understand, making it an ideal choice for learning programming. Basic Syntax Java uses a class-based object-oriented programming paradigm. Classes are templates that organize related data and behavior together. Here is a simple Java class example: publicclassPerson{privateStringname;privateintage;

Java Program to insert an element at the Bottom of a Stack Java Program to insert an element at the Bottom of a Stack Feb 07, 2025 am 11:59 AM

A stack is a data structure that follows the LIFO (Last In, First Out) principle. In other words, The last element we add to a stack is the first one to be removed. When we add (or push) elements to a stack, they are placed on top; i.e. above all the

Comparing Two ArrayList In Java Comparing Two ArrayList In Java Feb 07, 2025 pm 12:03 PM

This guide explores several Java methods for comparing two ArrayLists. Successful comparison requires both lists to have the same size and contain identical elements. Methods for Comparing ArrayLists in Java Several approaches exist for comparing Ar

See all articles