Semiprime | Rosetta Code | #4

URL to the problem page: https://rosettacode.org/wiki/Semiprime


Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers.

Semiprimes are also known as:
  • bi-primes 
  • 2-almost primes

Generate and show here, the semiprimes which are smaller than 100.



#include <iostream>
using namespace std;

bool primecheck(int a) {
    int counter = 0;
    for (int i = 2; i <= (a / 2); i++) {
        if (a % i == 0) {
            counter++;
            break;
        }
    }
    if (counter == 0) {
        return 1;
    }
    else {
        return 0;
    }
}

int main()
{
    int counter, a, prime;
    
    cout << "Semiprimes which are smaller than 100 are:" << endl;
    for (int i = 1; i < 100; i++) {
        counter = 0;
        for (int j = 2; j <= (i / 2); j++) {
            if (i % j == 0) {
                counter++;
            }
            if (counter > 2) {
                break;
            }
        }
        if (counter == 1) {
            int divisor;
            for (int k = 2; k <= (i / 2); k++) {
                if (i % k == 0) {
                    divisor = k;
                    break;
                }
            }
            if (primecheck(divisor) == 1) {
                cout << i << endl;
            }
        }
        else if (counter == 2) {
            int divisors[2];
            a = 0;
            prime = 0;
            for (int k = 2; k <= (i / 2); k++) {
                if (i % k == 0) {
                    divisors[a] = k;
                    a++;
                }
            }
            for (int b = 0; b < 2; b++) {
                if (primecheck(divisors[b]) == 0) {
                    prime++;
                }
            }
            if (prime == 0) {
                cout << i << endl;
            }
        }
    }
    return 0;
}



Comments

My photo
Ercan Tomac
instagram.com/ercantomac