Program to check Niven Number (Java)

 So today we are going to see What is Niven Number? and how to check a given number is Niven Number or Not.
So lets get started.


Q. Write a program to accept a number and check and display whether it is a Niven Numberor Not.
[Niven number is that number which is divisible by its sum of digits.]
For Example: Input: 126, its sum of digits = 1+2+6=9 and 126 is divisible by 9. So 126 is Niven.

Solution:
1234567891011121314151617181920212223242526272829 import java.util.*;
 class NivenNumber
 {
     public static void main()
     {
         Scanner sc = new Scanner(System.in);
         System.out.println("Enter a number: ");
         int n = sc.nextInt();
         int reminder,sum = 0;
         for(int i = n;i > 0;i=i/10)
         {
             reminder = i%10;
             sum = sum+reminder;
         }
         System.out.println("OUTPUT: ");
         System.out.println("Sum = " + sum);
         if(n%sum == 0)
         {
             System.out.println(n + " is divisble by " + sum);
             System.out.println("So, " + n + " is a Niven Number");
         }
         else
         {
             System.out.println(n + " is not divisble by " + sum);
             System.out.println(n + " is not a Niven Number");
         }
     }
 }

Code Written in BlueJ

Output:
1234567Enter a number: 
126
OUTPUT: 
Sum = 9
126 is divisble by 9
So, 126 is a Niven Number

Output in BlueJ

Variable description used in program:
int n - It is used to accept input from user.
int reminder - It is used to take last digit from the number i.e., reminder.
int sum - It is used to add the digits of the number.

So that is it for the Niven Number program. Hope you find it useful and if you have any query do comment in the comment box and I will try to solve your query. Will see you on next program.

Thank You.
Program to check Niven Number (Java) Program to check Niven Number (Java) Reviewed by Get2Know on September 27, 2020 Rating: 5

No comments:

Powered by Blogger.