Sphenic Number in Java

In this tutorial, we will start by learning what is Sphenic Number and write a Java Program to check for the Sphenic Number.

Sphenic Number

A Sphenic Number is a positive integer n which is a product of exactly three distinct prime numbers. Or we can say that n is a sphenic integer if n = a * b * c (a, b, and c are three distinct prime numbers and their product is equal to n).

Example: 30, 42, 66, 70, 78, 102, 105, etc.

Explanation:

Input : 110
Output : Yes
Explanation : Factors of 110 are = 1, 2, 5, 10, 11, 22,55 and 110
              Take the smallest three prime factors: 2, 5, 11
               Product of these smallest prime factors:  2*5*11
                                                                                        = 110
                                                                                        = Input =110
               Hence the number is Sphenic Number.

Java Program to Check if the Number is Sphenic Number or not

import java.util.*;

public class SphenicNumberExample1
{
   static boolean arr[] = new boolean[10000];

   static void findPrime()
   {
      Arrays.fill(arr, true);

      for (int p = 2; p * p < 10000; p++)
      {
         //if p is not changed, then it is a prime  
         if (arr[p])
         {
            for (int i = p * 2; i < 10000; i = i + p)
               arr[i] = false;
         }
      }
   }
 
   //checks if the given number is sphenic or not  
   static int isSphenic(int N)
   {
      int[] arr1 = new int[8];
      int count = 0, j = 0;

      for (int i = 1; i <= N; i++)
      {
         if (N % i == 0 && count < 8)
         {
            //increments the count by 1      
            count++;
            arr1[j++] = i;
         }
      }

      if (count == 8 && (arr[arr1[1]] && arr[arr1[2]] && arr[arr1[3]]))
         return 1;
      return 0;
   }

   //main function
   public static void main(String args[])
   {
      int n, result;

      findPrime();
      Scanner sc = new Scanner(System.in);

      System.out.print("Enter a number: ");
      n = sc.nextInt();

      result = isSphenic(n);

      if (result == 1)
         System.out.print(n + " is a sphenic Number.");
      else
         System.out.print(n + " is not a sphenic Number.");
   }
}

Output:

//First Execution
Enter a number: 30
30 is a sphenic Number.

//Second Execution
Enter a number: 165
165 is a sphenic Number.