Java program for Niven or Harshad number

Java program for Niven or Harshad number


ICSE 2016 Question 8 solution

Write a program to accept a number and check and display whether it is a Niven number or not.
(Niven number is the number which is divisible by its sum of digits it is also called Harshad number)
Example:
Consider the number 126
Sum of its digits is 1 + 2 + 6 = 9 and 126 is divisible by 9



Solution:
import java.util.*;
/**
 * class Niven Or Harshad Number
 * @author (Khurshid Md Anwar)
*/
public class NivenOrHarshadNumber
{
    public static void main(String args[])
    {
        int n, s, a, p;
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number : ");
        n = sc.nextInt();   // take the number
        p = n;
        s=0;                // initialize s for summation as 0
        while(n!=0)
        {
            a = n % 10;     // mod division for reminder
            s = s + a;      // sum the reminder
            n = n / 10;     // integer division
        }
        // check the summation whether it is divisble by entered number
        // or not
        if(p % s == 0)
        {
            System.out.println("It is a Niven / Harshad Number");
        }
        else
        {
            System.out.println("It is not a Niven / Harshad Number");
        }
    }
}

Output:
Enter a number : 126
It is a Niven / Harshad Number

Enter a number : 125


It is not a Niven / Harshad Number

More programs:

Java program to print Twin Prime Numbers


Some of the Good Books for ICSE exam 2017


SHARE THIS
Previous Post
Next Post