Open In App

Coprime Counting

Last Updated : 10 Dec, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

You are given an integer n. Determine how many pairs of integers (A, B) satisfy the conditions:

  • 0 <= A <= B <= n
  • gcd(A, B) = 1

Examples:

Input: 1
Output: 2
Explanation: Two pairs that satisfy the condition are (0, 1) and (1, 1)

Input: 6
Output: 13
Explanation: The pairs that satisfy the condition are (0,1), (1,1), (1,2), (1,3), (2,3), (1,4), (3,4), (1,5), (2,5), (3,5), (4,5), (1,6) and (5,6)

[Naive Approach] Check GCD for Every Pair — O(n² log n) Time and O(1) Space

The simplest way to solve the problem is to generate every possible pair (A, B) such that
0 ≤ A ≤ B ≤ n, and check if gcd⁡(A, B) = 1.

This method is easy to understand but extremely slow for large n.

C++
#include <iostream>
#include <algorithm>
using namespace std;

int coprimePairs(int n) {
    
    int result = 0;

    for (int B = 0; B <= n; B++) {
        for (int A = 0; A <= B; A++) {
            if (__gcd(A, B) == 1) {
                result++;
            }
        }
    }
    return result;
}

int main() {
    int n = 6;

    cout << coprimePairs(n);
    return 0;
}
Java
public class Main {

    public static int coprimePairs(int n) {
        int result = 0;

        for (int B = 0; B <= n; B++) {
            for (int A = 0; A <= B; A++) {
                if (gcd(A, B) == 1) {
                    result++;
                }
            }
        }
        return result;
    }

    // gcd function
    public static int gcd(int a, int b) {
        if (b == 0) return a;
        return gcd(b, a % b);
    }

    public static void main(String[] args) {
        int n = 6;
        System.out.println(coprimePairs(n));
    }
}
Python
import math

def coprimePairs(n):

    result = 0

    for B in range(n + 1):
        for A in range(B + 1):
            if math.gcd(A, B) == 1:
                result += 1

    return result

n = 6
print(coprimePairs(n))
C#
using System;

class GFG {
    static int coprimePairs(int n)
    {
        int result = 0;

        for (int B = 0; B <= n; B++)
        {
            for (int A = 0; A <= B; A++)
            {
                if (GCD(A, B) == 1)
                {
                    result++;
                }
            }
        }
        return result;
    }

    // gcd function
    static int GCD(int a, int b)
    {
        if (b == 0) return a;
        return GCD(b, a % b);
    }

    static void Main(string[] args) {
        int n = 6;
        Console.WriteLine(coprimePairs(n));
    }
}
JavaScript
function gcd(a, b) {
    while (b !== 0) {
        let temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

function coprimePairs(n) {

    let result = 0;

    for (let B = 0; B <= n; B++) {
        for (let A = 0; A <= B; A++) {
            if (gcd(A, B) === 1) {
                result++;
            }
        }
    }
    return result;
}

let n = 6;
console.log(coprimePairs(n));

Output
13

[Expected Approach] Using Euler Totient Function (φ) — O(n log log n) Time and O(n) Space

Instead of checking every pair, we use number theory.
For every number B:

  • The number of integers A such that 1 ≤ A < B and gcd⁡(A, B) = 1 is exactly φ(B), Euler’s Totient Function.

Additionally, there are two special valid pairs: (0, 1) and (1, 1)
Thus, the total number of valid pairs is:

Total = 2 + \sum_{B=2}^{n} \varphi(B)

To compute φ for all numbers efficiently, we use a sieve-like method similar to the Sieve of Eratosthenes.

Let B have a prime factorization:

B = p_1^{a_1} p_2^{a_2} \cdots p_k^{a_k}

An integer A (with 1 ≤ A < B) is not coprime with B if it shares at least one prime factor with B.
The count of numbers from 1 to B−1 that are divisible by each prime pi is: B/pi

Using the Inclusion–Exclusion Principle, Euler showed that:

\phi(B) = B(1 - \frac{1}{p_1})(1 - \frac{1}{p_2}) \cdots (1 - \frac{1}{p_k})

This formula counts exactly the numbers that do NOT share any prime factor with B.

C++
#include <iostream>
#include <vector>
using namespace std;

int coprimePairs(int n) {
    
    vector<int> phi(n + 1);

    // initialize phi[i] = i
    for (int i = 0; i <= n; i++) {
        phi[i] = i;
    }

    // compute totient using sieve
    for (int i = 2; i <= n; i++) {
        if (phi[i] == i) {          // i is prime
            for (int j = i; j <= n; j += i) {
                phi[j] -= phi[j] / i;
            }
        }
    }

    int result = 0;

    // sum φ(B) for B = 2 to n
    for (int i = 2; i <= n; i++) {
        result += phi[i];
    }

    // add pairs (0,1) and (1,1)
    if (n >= 1) {
        result += 2;
    }

    return result;
}

int main() {
    int n = 6;

    cout << coprimePairs(n);
    return 0;
}
Java
import java.util.Arrays;

public class Main {

    public static int coprimePairs(int n) {

        int[] phi = new int[n + 1];

        // initialize phi[i] = i
        for (int i = 0; i <= n; i++) {
            phi[i] = i;
        }

        // compute totient using sieve
        for (int i = 2; i <= n; i++) {
            if (phi[i] == i) { // i is prime
                for (int j = i; j <= n; j += i) {
                    phi[j] -= phi[j] / i;
                }
            }
        }

        int result = 0;

        // sum φ(B) for B = 2 to n
        for (int i = 2; i <= n; i++) {
            result += phi[i];
        }

        // add pairs (0,1) and (1,1)
        if (n >= 1) {
            result += 2;
        }

        return result;
    }

    public static void main(String[] args) {
        int n = 6;
        System.out.println(coprimePairs(n));
    }
}
Python
def coprimePairs(n):

    phi = [i for i in range(n + 1)]

    # compute totient using sieve
    for i in range(2, n + 1):
        if phi[i] == i:  # i is prime
            for j in range(i, n + 1, i):
                phi[j] -= phi[j] // i

    result = 0

    # sum φ(B) for B = 2 to n
    for i in range(2, n + 1):
        result += phi[i]

    # add pairs (0,1) and (1,1)
    if n >= 1:
        result += 2

    return result


n = 6
print(coprimePairs(n))
C#
using System;

class GFG
{
    static int coprimePairs(int n)
    {
        int[] phi = new int[n + 1];

        // initialize phi[i] = i
        for (int i = 0; i <= n; i++)
        {
            phi[i] = i;
        }

        // compute totient using sieve
        for (int i = 2; i <= n; i++)
        {
            if (phi[i] == i) // i is prime
            {
                for (int j = i; j <= n; j += i)
                {
                    phi[j] -= phi[j] / i;
                }
            }
        }

        int result = 0;

        // sum φ(B) for B = 2 to n
        for (int i = 2; i <= n; i++)
        {
            result += phi[i];
        }

        // add pairs (0,1) and (1,1)
        if (n >= 1)
        {
            result += 2;
        }

        return result;
    }

    static void Main()
    {
        int n = 6;
        Console.WriteLine(coprimePairs(n));
    }
}
JavaScript
function coprimePairs(n) {

    let phi = new Array(n + 1);

    // initialize phi[i] = i
    for (let i = 0; i <= n; i++) {
        phi[i] = i;
    }

    // compute totient using sieve
    for (let i = 2; i <= n; i++) {
        if (phi[i] === i) { // i is prime
            for (let j = i; j <= n; j += i) {
                phi[j] -= Math.floor(phi[j] / i);
            }
        }
    }

    let result = 0;

    // sum φ(B) for B = 2 to n
    for (let i = 2; i <= n; i++) {
        result += phi[i];
    }

    // add pairs (0,1) and (1,1)
    if (n >= 1) {
        result += 2;
    }

    return result;
}

let n = 6;
console.log(coprimePairs(n));

Output
13

Time Complexity: O(n log log n) - computing φ using the sieve takes O(n log log n) time because each prime updates its multiples, and the sum of reciprocals of all primes up to n grows like log log n.
Space Complexity: O(n) - for storing the φ array.


Article Tags :

Explore