Java Program To Check Niven or Harshad Number or Not
Niven Number or Harshad Number
In mathematics, A Harshad Number (or Niven number) in a given number
base is an integer that is divisible by the sum of its digits
when written in that base. Harshad numbers in base n are also known as
n-harshad (or n-Niven) numbers.
Example :
Given Number : 36
Sum of its Digits : 3 + 6 = 9
36 is a Niven or Harshad Number
Since ,
36 is Divisible By The Sum of Its Digits
you can use the following algorithm:
- Read the input number.
- Initialize a variable sum to 0.
- Create a copy of the input number.
- While the number is not equal to 0, perform the following steps:
- Get the last digit of the copy by using the modulo operator (%).
- Add the last digit to the sum.
- Divide the number by 10 to remove the last digit.
- Check if the copy of number is divisible by the sum .
- If the input number is divisible, it is a Niven or Harshad number.
Otherwise, it is not. - Print the result.
In this algorithm, the input number is processed by extracting each digit and adding it to the sum variable. Then, the copy of input number is checked if it is divisible by the sum. If it is divisible, the number is considered a Niven or Harshad number.
Please note that this implementation assumes that the input number is a positive integer. You may need to add additional checks for negative numbers or other cases depending on your requirements.
Here is an example implementation in Java
Source Code
//Java Program To Check Niven or Harshad Number or Not
import java.util.*;
public class NivenOrHarshadNumber
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
int num ,Rd,sum=0,ncopy;
System.out.print("Enter a Number To Check : ");
num=in.nextInt();
ncopy=num;
while(num!=0)
{
Rd = num % 10 ;
sum= sum + Rd ;
num= num / 10 ;
}
if(ncopy%sum==0)
System.out.print("It is a Niven Or Harshad Number . ");
else
System.out.print("It is Not a Niven Or Harshad Number . ");
}
}
Output
Sample Input :
Enter a Number To Check : 12
Sample Output:
It is a Niven Or Harshad Number
Sample Input :
Enter a Number To Check : 15
Sample Output:
It is Not a Niven Or Harshad Number
Looping Related Programs
- Java Program to Check Prime Number or Not
- Java Program to Check Twin Prime Number or Not
- Java Program to Check Perfect Number or Not
- Java Program to Check Spy Number or Not
- Java Program to Check Neon Number or Not
- Java Program to Check Duck Number or Not
- Java Program to Check Niven or Harshad Number or Not
- Java Program to Check Palindrome Number or Not
- Java Program to Check Armstrong Number or Not
- Java Program to Check Strong (Krishnamurthy) Number or Not
- Java Program to Check Automorphic Number or Not
- Java Program to Check Happy Number Or Not