Subscribe Us

Niven Or Harsahd Number In Java

Niven Or Harshad Number In Java


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

To check if a number is a Niven or Harshad number in Java
you can use the following algorithm:
  1. Read the input number.
  2. Initialize a variable sum to 0.
  3. Create a copy of the input number.
  4. 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.
  5. 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.
  6. 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