Google News
logo
Java Program to Smith Number
A Smith number is a composite number whose sum of digits is equal to the sum of digits of its prime factors (excluding 1) when written in prime factorization form.

For example, 22 is a Smith number as it can be factored as 2 x 11 and 2 + 2 = 4, and the sum of digits of 2 and 11 is also 4.

Here's a Java program to check if a number is a Smith number or not :
Program :
import java.util.Scanner;

public class SmithNumber {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = sc.nextInt();
        sc.close();
        int sumOfDigits = getSumOfDigits(num);
        int sumOfPrimeFactors = getSumOfPrimeFactors(num);
        if (sumOfDigits == sumOfPrimeFactors) {
            System.out.println(num + " is a Smith number.");
        } else {
            System.out.println(num + " is not a Smith number.");
        }
    }

    // Method to get the sum of digits of a number
    private static int getSumOfDigits(int num) {
        int sum = 0;
        while (num > 0) {
            sum += num % 10;
            num /= 10;
        }
        return sum;
    }

    // Method to get the sum of prime factors of a number
    private static int getSumOfPrimeFactors(int num) {
        int sum = 0;
        for (int i = 2; i <= num; i++) {
            while (num % i == 0) {
                sum += getSumOfDigits(i);
                num /= i;
            }
        }
        return sum;
    }
}
Output :
Enter a number: 22
22 is a Smith number.
Enter a number: 21
21 is not a Smith number.
In the above program, we first take the input number from the user and then calculate the sum of its digits using the getSumOfDigits() method.

Next, we calculate the sum of digits of its prime factors (excluding 1) using the getSumOfPrimeFactors() method. Finally, we check if both the sums are equal or not to determine if the number is a Smith number or not.