Write a java program to determine whether a given number is a Harshad number


Harshad Number

A number is said to be harshad number , If it is divisible by the sum of its digit.

For example-

Let number be 18

Sum of digit of 18 id 1 + 8 = 9

Hence, 18 is divisible by 9 , therefore 18 is harshad number.

Some of the example of harshad number are 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42, 45, 48, 50, 54, 60, 63, 70, 72, 80, 81, 84, 90, 100, 102, 108, 110, 111, 112, 114, 117, 120, 126, 132, 133, 135, 140, 144, 150, 152, 153, 156, 162, 171, 180, 190, 192, 195, 198, 200, ...

Algorithm to find whether the given number is Harshad number or not.

  1. Declare and initialize value for remainder = 0 , sum = 0, n, num .
  2. Now take user input as a integer for variable num.
  3. Copy the value of variable num into n.
  4. Now check if num is greater than 0, then calculate the remainder by dividing it with 10
  5. Add that remainder to the sum.
  6. Now Divide num by 10.
  7. Repeat the step from 3 to 5 , till num become less than 0.
  8. Atlast divide n with sum, if remainder is 0, then it is harshad number, else the user input is not a harshad number.
Program
import java.util.*; public class Harshad { public static void main(String[] args) { Scanner s=new Scanner(System.in); int num=s.nextInt(); int rem = 0, sum = 0, n; n = num; while(num > 0){ rem = num%10; sum = sum + rem; num = num/10; } if(n%sum == 0) System.out.println(n + " is a Harshad number"); else System.out.println(n + " is not a Harshad number"); } }
Input
Output