search
HomeJavajavaTutorialHow 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
javanumberexamineharshad 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);

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();

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’;

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");
   }
}

Output

Given number: 21
21 is a Harshad number

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");      
   }
}

Output

Given number: 40
40 is a Harshad number

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
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
What are the advantages of using bytecode over native code for platform independence?What are the advantages of using bytecode over native code for platform independence?Apr 30, 2025 am 12:24 AM

Bytecodeachievesplatformindependencebybeingexecutedbyavirtualmachine(VM),allowingcodetorunonanyplatformwiththeappropriateVM.Forexample,JavabytecodecanrunonanydevicewithaJVM,enabling"writeonce,runanywhere"functionality.Whilebytecodeoffersenh

Is Java truly 100% platform-independent? Why or why not?Is Java truly 100% platform-independent? Why or why not?Apr 30, 2025 am 12:18 AM

Java cannot achieve 100% platform independence, but its platform independence is implemented through JVM and bytecode to ensure that the code runs on different platforms. Specific implementations include: 1. Compilation into bytecode; 2. Interpretation and execution of JVM; 3. Consistency of the standard library. However, JVM implementation differences, operating system and hardware differences, and compatibility of third-party libraries may affect its platform independence.

How does Java's platform independence support code maintainability?How does Java's platform independence support code maintainability?Apr 30, 2025 am 12:15 AM

Java realizes platform independence through "write once, run everywhere" and improves code maintainability: 1. High code reuse and reduces duplicate development; 2. Low maintenance cost, only one modification is required; 3. High team collaboration efficiency is high, convenient for knowledge sharing.

What are the challenges in creating a JVM for a new platform?What are the challenges in creating a JVM for a new platform?Apr 30, 2025 am 12:15 AM

The main challenges facing creating a JVM on a new platform include hardware compatibility, operating system compatibility, and performance optimization. 1. Hardware compatibility: It is necessary to ensure that the JVM can correctly use the processor instruction set of the new platform, such as RISC-V. 2. Operating system compatibility: The JVM needs to correctly call the system API of the new platform, such as Linux. 3. Performance optimization: Performance testing and tuning are required, and the garbage collection strategy is adjusted to adapt to the memory characteristics of the new platform.

How does the JavaFX library attempt to address platform inconsistencies in GUI development?How does the JavaFX library attempt to address platform inconsistencies in GUI development?Apr 30, 2025 am 12:01 AM

JavaFXeffectivelyaddressesplatforminconsistenciesinGUIdevelopmentbyusingaplatform-agnosticscenegraphandCSSstyling.1)Itabstractsplatformspecificsthroughascenegraph,ensuringconsistentrenderingacrossWindows,macOS,andLinux.2)CSSstylingallowsforfine-tunin

Explain how the JVM acts as an intermediary between the Java code and the underlying operating system.Explain how the JVM acts as an intermediary between the Java code and the underlying operating system.Apr 29, 2025 am 12:23 AM

JVM works by converting Java code into machine code and managing resources. 1) Class loading: Load the .class file into memory. 2) Runtime data area: manage memory area. 3) Execution engine: interpret or compile execution bytecode. 4) Local method interface: interact with the operating system through JNI.

Explain the role of the Java Virtual Machine (JVM) in Java's platform independence.Explain the role of the Java Virtual Machine (JVM) in Java's platform independence.Apr 29, 2025 am 12:21 AM

JVM enables Java to run across platforms. 1) JVM loads, validates and executes bytecode. 2) JVM's work includes class loading, bytecode verification, interpretation execution and memory management. 3) JVM supports advanced features such as dynamic class loading and reflection.

What steps would you take to ensure a Java application runs correctly on different operating systems?What steps would you take to ensure a Java application runs correctly on different operating systems?Apr 29, 2025 am 12:11 AM

Java applications can run on different operating systems through the following steps: 1) Use File or Paths class to process file paths; 2) Set and obtain environment variables through System.getenv(); 3) Use Maven or Gradle to manage dependencies and test. Java's cross-platform capabilities rely on the JVM's abstraction layer, but still require manual handling of certain operating system-specific features.

See all articles

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

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.