VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-whether-number-semiprime-not/

⇱ Check whether a number is semiprime or not - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check whether a number is semiprime or not

Last Updated : 9 Dec, 2023

Given a positive integer n. Find whether a number is a semiprime or not. Print True if number is semiprime else False. A semiprime is a natural number that is a product of two prime numbers.
Examples :

Input: 6
Output: True
Explanation
6 is a semiprime number as it is a
product of two prime numbers 2 and 3.
Input: 9
Output: True
Input: 8
Output: False
Recommended Practice

Approach: The approach is simple, factorize the given number by dividing it with the divisor of a number to remove the composite number. Meanwhile, keep updating the count variable of the prime number.

Below is the implementation of the above approach:


Output
True
False

Time Complexity: O(
Auxiliary space: O(1)

Another Approach: To check whether a number is a semiprime or not, the idea is to factorize the given number into its prime factors. If the number has exactly two prime factors, then it is a semiprime. Below are the steps:

  1. Take input a positive integer N.
  2. Iterate from [2, N/2] and check if N is divisible by any of the numbers in the range then check if both the divisor and quotient are prime numbers. If yes, then the number is semiprime. Otherwise, it is not a semiprime number.

Below is the implementation of the above approach:


Output
True

Time Complexity: O(N*log(log(N)))
Auxiliary Space: O(1)

Comment