Write a program to accept a number and check and display whether it is a Niven number or not. A Niven number is a number which is divisible by the sum of its digits. Example: consider the number 126. Sum of its digits is 1 + 2 + 6 = 9, and 126 is divisible by 9.
Topic: Checking for a Niven number
Answer
import java.util.Scanner;
class Niven { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.print("Enter a number : "); int n = sc.nextInt();
int num = n, sum = 0;
while(num > 0) { sum = sum + num % 10; num = num / 10; }
System.out.println("Sum of digits = " + sum);
if(n % sum == 0) System.out.println(n + " is a Niven number"); else System.out.println(n + " is not a Niven number"); } }
A short program that depends entirely on one habit: keeping the original number safe.
The digit-extraction loop destroys num as it works, reducing it to 0. But the final test needs the ORIGINAL number — n % sum — so n must never enter the loop. Candidates who loop on n itself find that n has become 0 by the time they need it, and 0 % sum is 0, which reports every number as Niven.
The extraction itself is the standard pair: num % 10 takes the last digit num / 10 removes it, by integer division running while num > 0.
Trace 126: digits 6, 2, 1 give sum = 9, and 126 % 9 = 0, so it is a Niven number — matching the question. Trace 123: sum = 6 and 123 % 6 = 3, so it is not.
n int - the number entered by the user (kept unchanged) num int - working copy of n, reduced digit by digit sum int - running total of the digits sc Scanner - object used to read input