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 , which is divisible.
- 19 is not a Harshad number because , 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
Input:
- The program reads a number
nfrom the user.
- The program reads a number
Calculate the Sum of Digits:
- Use a
whileloop to repeatedly extract the last digit of the number (temp % 10). - Add the digit to the
sumand remove it from the number by dividingtempby 10 (temp /= 10).
- Use a
Check Divisibility:
- Use the modulo operator (
%) to check ifnis divisible bysum.
- Use the modulo operator (
Output:
- Print "Yes" if the number is a Harshad number, otherwise print "No."
Example Input and Output
Input:
Process:
Output:
Input:
Process:
Output:
Edge Cases
Single-digit Numbers:
- All single-digit numbers (1-9) are Harshad numbers since any number is divisible by itself.
Zero:
- Mathematically, zero is not considered a Harshad num
No comments:
Post a Comment