Niven Number | Write a program in Java to check if the given number is NIven Number or not. | ISC Computer Science | ICSE Computer Application
Harshad Number : In recreational mathematics, a Harshad number (or Niven number), is an integer (in base 10) that is divisible by the sum of its digits.
Algorithm
- Start
- x:=0
- Print "Enter a number"
- Read x
- if x%step 6 ==0, go to step 15 or else go to step 16
- t=x. Go to step 7
- digit:=0. Go to step 8
- sum=0. Go to step 9
- if t>0, go to step 10 or else go to step 14
- digit=t%10. Go to step 11
- sum=sum+digit. Go to step 12.
- t=t/10. Go to step 13
- Go to step 9
- return sum
- Print "The given number is Niven Number". Go to step 17
- Print "The given number is not Niven Number"
- Stop
Program
Buffered Reader
import java.io.*;
class Niven
{
int x;
void accept() throws IOException
{
BufferedReader br=new BufferedReader (new InputStreamReader (System.in));
System.out.println("Enter a number");
x=Integer.parseInt(br.readLine());
}
int sumOfDigits()
{
int t=x, digit, sum=0;
while(t>0)
{
digit=t%10;
sum=sum+digit;
t=t/10;
}
return sum;
}
void isNiven()
{
if(x%sumOfDigits()==0)
{
System.out.println("The given number is Niven Number");
}
else
{
System.out.println("The given number is not a Niven Number");
}
}
void main() throws IOException
{
accept();
isNiven();
}
}
Scanner
import java.util.*;
class Niven
{
int x;
void accept()
{
Scanner sc=new Scanner(Sysem.in);
System.out.println("Enter a number");
x=sc.nextInt();
}
int sumOfDigits()
{
int t=x, digit, sum=0;
while(t>0)
{
digit=t%10;
sum=sum+digit;
t=t/10;
}
return sum;
}
void isNiven()
{
if(x%sumOfDigits()==0)
{
System.out.println("The given number is Niven Number");
}
else
{
System.out.println("The given number is not a Niven Number");
}
}
void main()
{
accept();
isNiven();
}
}
Documentation
Variable Description
Data Type | Variable Name | Description |
int | x | To store the number entered by the user. |
int | t | To act as a temp variable |
int | digit | To store the digit of the number |
int | sum | To store the sum of digits of the number |
Method Description
Return Type | Method Name | Description |
void | accept() | To accept data from the user. |
int | sumOfDigits() | To calculate the sum of digits of the number. |
void | isNiven() | To check whether the given number is Niven or not. |
void | main() | To act as an entry gateway for the compiler. |
Output
Share with all ISC Computer Science Students you know.
Comment below with all your program requests and blog suggestions.
Follow us on social media by clicking on these links.
Instagram : @IscJavaCode
Twitter: @IscCode
Quora: ISC Java Code
Stay Healthy
Stay Happy
Stay Helpful
Comments
Post a Comment