Niven/Harshad Number in JAVA
Niven/Harshad Number in JAVA
A positive integer which is divisible by the sum of its digits, also called a Niven/Harshad number.
Example - 81 is divisible by 8+1= 9 . 81 is Niven Number.
Algorithm and Program below :-
ALGORITHM :-
- Input a number to check for Niven Number
- Store it in a new variable
- Store the sum of its digit in a variable
- Check if the number is divisible by the sum of digits without leaving remainder
- If it is divisible print "It is Niven Number"
- If not print "It is not Niven Number"
PROGRAM Below :-
import java.io.*;
import java.util.*;
class Niven
{
public static void main(String args[])
{
Scanner in= new Scanner(System.in);
int n,p,rev,s=0;
System.out.println("Enter Number");
n= in.nextInt(); // Input number from user
p=n; // store the entered number in "p" variable
while(n>0)
{
rev=n%10; // extract last digit of the number
s=s+rev; // store the sum of digits
n=n/10; // extract all digit except the last
}
if(p%s==0) // if number is divisible by sum of digits leaving no remainder
{
System.out.println("It is Niven/Harshad Number : "+p);
}
else
{
System.out.println("It is not Niven/Harshad Number : "+p);
}
} // end of main method
Comments
Post a Comment