In the previous article, we have discussed Java Program to Check Mystery Number

In this article we are going to understand what Smith number is and how we can check whether a number is Smith or not in Java with examples.

## Program to Check Smith Number

**Smith numbers** are numbers whose sum of digits of all its prime factors other than 1 and sum of its digits are equal.

Example :

- 85: Sum = 8+5 = 13; Prime Factors(5,17)

Sum of digits of its prime factors = 5+1+7 = 13 Smith number

- 999: Sum = 9+9+9 = 27; Prime Factors(3,3,3,37)

Sum of digits of its prime factors = 3+3+3+3+7 = 19 Not a Smith number

In the above examples the number 85 is a Smith numbers as its sum of digits and sum of digits of its prime factors are equal i.e. 13. However 999 is not a smith number as both the numbers are different.

If you are new to Java and want to learn the java coding skills too fast. Try practicing the core java programs with the help of the Java basic programs list available.

**Approach :**

- We ask the user to enter a number and store it .
- Then we calculate the prime factors and then add their digits and store them. Then the digits of the number are added together.
- If both the sums are equal, then the number is said to be a Smith number.

**Program:**

Let’s see the program to understand it more clearly.

import java.util.Scanner; public class SmithNumber{ public static void main(String args[]) { //Tanuming the number as input from the user using scanner class Scanner scan = new Scanner(System.in); System.out.print("Enter a number : "); int num = scan.nextInt(); // Checks whether the number is Smith number or not if(primeFactorSum(num)==digitSum(num)) { System.out.println(num+" is a Smith number"); } else { System.out.println(num+" is Not a Smith number"); } } // Returns the sum of digits of the prime factors static int primeFactorSum(int num) { int i=2, sum=0; while(num>1) { if(num%i==0) { sum=sum+digitSum(i); num=num/i; } else { do { i++; } while(!isPrime(i)); } } return sum; } //function finds the sum of digits of the given numbers static int digitSum(int num) { int sum=0; while(num>0) { sum=sum+num%10; num=num/10; } //returns the sum of digits of the number return sum; } //function checks if the factor is prime or not static boolean isPrime(int num) { boolean flag=true; int div=2; while(div<Math.sqrt(num)) { if(num%div==0) { flag=false; } div++; } return flag; } }

Output: Case-1 Enter a number : 19 19 is a Smith number Case-2 Enter a number : 699 699 is Not a Smith number

Are you wondering how to seek help from subject matter experts and learn the Java language? Go with these Basic Java Programming Examples and try to code all of them on your own then check with the exact code provided by expert programmers.

**Related Java Programs:**