Google News
logo
Java Program to Sphenic Number
A sphenic number is a positive integer that is the product of three distinct prime numbers. In other words, a sphenic number is a number that has exactly three distinct prime factors.

For example, 30 is a sphenic number because it is the product of 2, 3, and 5, which are all prime numbers.

Here is a Java program to check if a given number is a sphenic number or not :
Program :
import java.util.Scanner;

public class SphenicNumber {

    // Function to check if a number is sphenic or not
    public static boolean isSphenic(int n) {
        int count = 0;
        for (int i = 2; i <= n; i++) {
            if (n % i == 0) {
                count++;
                if (count > 3) {
                    return false;
                }
                n /= i;
                i--;
            }
        }
        return count == 3;
    }

    // Main method
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = sc.nextInt();

        if (isSphenic(num)) {
            System.out.println(num + " is a sphenic number.");
        } else {
            System.out.println(num + " is not a sphenic number.");
        }
    }
}
Output :
Enter a number: 30
30 is a sphenic number.
Enter a number: 37
37 is not a sphenic number.
In this program, the isSphenic() function takes an integer n as input and checks if it is a sphenic number or not. It uses a count variable to keep track of the number of distinct prime factors of n. If n is divisible by a prime number, the count is incremented, and the factor is removed from n. The loop continues until n has been completely factored or the count exceeds 3. If n has exactly 3 prime factors, the function returns true; otherwise, it returns false.

In the main method, we prompt the user to enter a number and then call the isSphenic() function to check if it is a sphenic number. If it is, we print a message indicating that it is a sphenic number; otherwise, we print a message indicating that it is not a sphenic number.