Checking semiprime numbers - JavaScript

We are required to write a JavaScript function that takes in a number and determines if the provided number is a semiprime or not.

What is a Semiprime?

A semiprime number is a special type of composite number that is the product of exactly two prime numbers (not necessarily distinct). For example:

  • 6 = 2 × 3 (product of two distinct primes)
  • 15 = 3 × 5 (product of two distinct primes)
  • 10 = 2 × 5 (product of two distinct primes)
  • 4 = 2 × 2 (square of a prime)
  • 9 = 3 × 3 (square of a prime)

Algorithm Approach

To check if a number is semiprime, we count its prime factors. If the total count equals exactly 2, it's a semiprime.

Semiprime Check Algorithm Input: num = 141 Count = 0 Find prime factors Count factors If count == 2: Semiprime If count != 2: Not semiprime

Example

Following is the code to check semi-prime numbers:

const num = 141;
const checkSemiprime = num => {
    let cnt = 0;
    let temp = num; // Keep original number for reference
    
    for (let i = 2; cnt  1) {
        ++cnt;
    }
    
    // Return true if count is equal to 2
    return cnt === 2;
}

console.log(`Is ${num} a semiprime?`, checkSemiprime(num));
Is 141 a semiprime? true

Testing Multiple Numbers

const checkSemiprime = num => {
    let cnt = 0;
    let temp = num;
    
    for (let i = 2; cnt  1) {
        ++cnt;
    }
    
    return cnt === 2;
}

// Test various numbers
const testNumbers = [4, 6, 9, 10, 15, 21, 25, 77, 141];

testNumbers.forEach(num => {
    console.log(`${num}: ${checkSemiprime(num) ? 'Semiprime' : 'Not semiprime'}`);
});
4: Semiprime
6: Semiprime
9: Semiprime
10: Semiprime
15: Semiprime
21: Semiprime
25: Semiprime
77: Semiprime
141: Semiprime

How It Works

The algorithm works by:

  1. Counting prime factors: For each potential divisor from 2 to ?num, divide out all occurrences
  2. Tracking the count: Each time we divide, increment the counter
  3. Handling remaining factor: If a number > 1 remains after division, it's also a prime factor
  4. Checking the result: A semiprime has exactly 2 prime factors (counting multiplicity)

Conclusion

A semiprime is the product of exactly two prime numbers. The algorithm efficiently counts prime factors and returns true when exactly two are found, making it suitable for identifying semiprimes in JavaScript applications.

Updated on: 2026-03-15T23:18:59+05:30

432 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements