Solution to the Codility Common Prime divisors Set Problem

This article discusses (a problem that I recently solved on codility ).

The core of the problem is the following:
Given two non negative integers N and M, 1 \leq M \leq N \leq 2147483647, the task is to check whether they have the same set of prime divisors.
A prime divisor of an integer P is a prime d s.t. d \times k = P for some positive k. You are given up to 6 \times 10^3 of such queries, and should return the total number of them that evaluates to true.

For instance given if N = 156 and M = 78 then our function should return *true* because the set of prime divisor of N is equal the
the set of primal divisor of M i.e. \{2,13,3\} while for N=45 and M=120 the function should return *false*.

Smart (not enough) Brute Force approach

An easy approach in solving this problem could be computing by bruteforce the set of prime divisors of both numbers and compare them, and return true if they contains the same elements.
In order to achieve that we should:

    1. compute the set of primes up to L=max(N,M). There are approximately \frac{L}{log (L - 1)} (Read here for a more info on this topic
    2. Using the Sieve of Έρατοσθένης approach we are able to compute it in L \times (log (log (L))) time and space (see the following code).

void getPrimesSieve(vector<long long>&primes, const ll n) {
using ll = long;
    vector<bool> nums(n + 1, true);
    for (ll i = 3; i * i < n + 1; i += 2) {
        if (nums[i]) {
          for (ll j = i * i; j < n + 1; j += 2 * i) {
             nums[j] = false;

    for (ll i = 3 ; i <= n ; i += 2)
        if (nums[i])
    1. With the set of prime numbers in place then we can start finding the primal divisors. The following function computes the set of unique prime divisors of p and stores them in F.
bool primalDivisors( long p , vector<long>& F, vector<long>& primes) {
 int i = 0;
 int c = 0;
 if (i >= primes[primes.size()-1])
            return false;
    while (p > 1) {
        if (p % primes[i] == 0)
            p /= primes[i];
            if (c > 0) {
                c = 0;
    if (c > 0)

    return true;
    1. Finally we can iterate among all the queries and count the number of pairs returning *true*.
int solution(vector<int>& A,vector<int>& B){
	int LIM = -1;
	int ans = 0;
	LIM = max( *max_element(A.begin(), A.end()) ,*max_element(B.begin(), B.end()) ) ;
	vector<int> primes;
	getPrimesSieve(primes, LIM);

	for (unsigned i = 0; i < A.size(); ++i)
		vector<int> divA;
		vector<int> divB;
		primalDivisors(A[i] , divA, primes);
		primalDivisors(B[i] , divB, primes);

//same set of divisors
		if( divA == divB)

	return ans;

Altough this approach is correct, it is too slow. There are \approx \frac{L}{log (L - 1)} = \frac{2147483647}{log (2147483647 - 1)} = 99940774 primes up to 2147483647. Since the primalDivisors function gets called up to K=6000 times and it has linear complexity then the overall time complexity is: K \frac{L}{log (L - 1)} which translates to \approx 6 \times 10^{11}!

Fast Approach using GCD

For two number to share the same set S of prime divisors it must be the case that S(N) \subseteq S(M) and S(M) \subseteq S(N). Checking if a number has a set of prime divisors that is subset of another is easy. In order for two number to have the same set of prime divisors the following must hold:
N = p_{0}^{a_0} \times p_1^{a_1} \ldots p_n^{a_n} and M = p_0^{b_0} \times p_1^{b_1} \ldots p_n^{b_n} i.e. their factorization only differ in the exponents.
Since clearly the GCD(M,N) \ne 1 we can divide M\ by it obtaining M' = \frac{M}{GCD(M,N)}. M' cannot have a larget set of factors than M and hence its set of prime divisor is still contained into N's one. We can keep repeating this process until M' becomes one.
Dividing by the GCD eliminates the common part of among the two number. And if eventually the dividend becomes 1, that means that the common part was the only part present.

As an example consider M = 2^2 \times 3^3 \times 5^2 and N = 2^1 \times 3^1 \times 5^1, GCD(M,N) = N and M' = 2^1 \times 3^2 \times 5^1. Repeting the process leads to GCD(M',N) = N and M'' = 3^1 and GCD(M'',N) = 3 and M''' = 1.
This shows that the set of prime divisor of M is contained in the set of prime divisor of N.
If we can show that the set of N is included in M's one, than the two sets must be equal. It is sufficient to do the same process with roles of N and M swapped.
If apply the same process to swapping the values of M and N from the previous example we obtain that M = 2^1 \times 3^1 \times 5^1 and N =2^2 \times 3^3 \times 5^2, GCD(M,N) = N and M' = 1.

If there is a divisor that is not common to both number then the process will eventually isolate it.
Imagine that M = 2^2 \times 3^3 \times 5^2 \times 11 and N = 2^1 \times 3^1 \times 5^1. All common divisors will be cancelled out by repeting the division by the GCD leaving M=11 and N=2^1 \times 3^1 \times 5^1.

Finally, the following is a possible implementation of the overall previous idea, which is also much simpler and cleaner than the one presented in the previous section.

bool containedSet(int M, int N){
	int g = __gcd(min(N,M), max(N,M));
    while(g != 1){
    	M /= g;
    	g = __gcd(min(N,M), max(N,M));
    return M==1;

int solution(vector<int>& A,vector<int>& B){
	int ans = 0;
	for (unsigned i = 0; i < A.size(); ++i)
	    //divisor A contained in divisor of B
	    //divisor A contained in divisor of A
	    //implies divisor A =  divisor of B
           if(containedSet(A[i],B[i]) && containedSet(B[i],A[i]))

	return ans;

2 thoughts on “Solution to the Codility Common Prime divisors Set Problem”

  1. I found this __gcd(min(N,M), max(N,M)) a little bit confusing.
    You can easly count gcd(N, M) first, than invoke something like containedSet(N, gcd_value) and containedSet(M, gcd_value). From my point of view it would be more clear and simple.

    1. I do not see why this is confusing. I always call __gcd() with the minimum of the two numbers as first argument. Nothing more than that.

Leave a Reply

Your email address will not be published. Required fields are marked *