16 May 2024

Harshad Number a number is divisible by sum of its digits

 Harshad Number:- A number is divisible by sum of its digits

A Harshad Number (or Niven Number) is an integer that is divisible by the sum of its digits. For example:

  • 18 is a Harshad number because 18÷(1+8)=, which is divisible.
  • 19 is not a Harshad number because 19÷(1+9)=1, which is not divisible.

import java.util.*;


class HelloWorld {

    public static void main(String[] args) {

        int n=sc.nextInt();

        int sum=0,temp=n;

        while(temp!=0){

            sum+=temp%10;

            temp/=10;

        }

        System.out.print(n%sum==0?"yes":"no");

    }

}

How It Works

  1. Input:

    • The program reads a number n from the user.
  2. Calculate the Sum of Digits:

    • Use a while loop to repeatedly extract the last digit of the number (temp % 10).
    • Add the digit to the sum and remove it from the number by dividing temp by 10 (temp /= 10).
  3. Check Divisibility:

    • Use the modulo operator (%) to check if n is divisible by sum.
  4. Output:

    • Print "Yes" if the number is a Harshad number, otherwise print "No."

Example Input and Output

Input:

18

Process:

  • 1+8=91 + 8 = 9
  • 18mod9=018 \mod 9 = 0

Output:

Yes, 18 is a Harshad number.

Input:

19

Process:

  • 1+9=101 + 9 = 10
  • 19mod10019 \mod 10 \neq 0

Output:

No, 19 is not a Harshad number.

Edge Cases

  1. Single-digit Numbers:

    • All single-digit numbers (1-9) are Harshad numbers since any number is divisible by itself.
  2. Zero:

    • Mathematically, zero is not considered a Harshad num

No comments:

Post a Comment