Niven (Or Harshad) Number in Java Trick 2024 | topperbhai.com

Niven (or Harshad) Number in Java

Niven (Or Harshad) Number in Java Trick

What Is  Harshad or Niven Number?

A number is said to be Harshad (or Niven) if it divisible by the sum of its digits.


For example, if number is 54, then sum of its digit will be 5 + 4 = 9. Since 54 is divisible by 9. So, 54 is a Harshad number.


Also Read:


In this tutorial, we will write a program to print the Niven (or Harshad) number in java using while loop.


 
First, we will write the niven  number in java algorithm, then we will write the complete java code of this program.


Niven Number in Java Algorithm:-

Step 1:  Initialize a number (n).

Step 2:  Make a copy of (n).

Step 3:   Extract the last digit (extract) of the number (n).

Step 4:   Store the sum of digits (sumofdigs) of the number (n).

Step 5:   Repeat steps 3 to 5 until the input number becomes 0.

Step 6:   If sum of digits are equal to the number entered, then the number is Niven else not.


The number 54 is a niven  number because  sum of digits  5 + 4 = 9 and 54 is completely divisible by 9.



Niven (or Harshad) Number In Java using while loop

 import java.util.*;  
 class Niven_Number  
 {  
   public static void main()  
   {  
     Scanner sc=new Scanner(System.in);  
     int n,extract=0,m,sumofdigs=0;  
     System.out.println("Enter any Number");  
     n=sc.nextInt();  
     m=n;  
     while(n!=0)  
     {  
       extract=n%10;  
       sumofdigs=sumofdigs+extract;  
       n=n/10;  
     }  
     if(m%sumofdigs==0)  
     {  
       System.out.println("It is a Niven Number");  
     }  
     else  
     {  
       System.out.println("Not a Niven Number");  
     }  
   }  
 }  
OUTPUT:
 Enter any Number  
 54  
 It is a Niven Number  

Post a Comment

0 Comments