Count of natural numbers in range [L, R] which are relatively prime with N

Given three integers N, L, and R. The task is to calculate the number of natural numbers in the range [L, R] (both inclusive) which are relatively prime with N.
Examples:Â Â
Input: N = 10, L = 1, R = 25Â
Output: 10Â
Explanation:Â
10 natural numbers (in the range 1 to 25) are relatively prime to 10.Â
They are 1, 3, 7, 9, 11, 13, 17, 19, 21, 23.Input: N = 12, L = 7, R = 38Â
Output: 11Â
Explanation:Â
11 natural numbers (in the range 1 to 38) are relatively prime to 12.Â
They are 7, 11, 13, 17, 19, 23, 25, 29, 31, 35, 37.Â
Approach:Â Â
- At first, factorize the number N. Thus, find out all the prime factors of N.
- Store prime factors of the number N in an array.
- We can determine the total number of natural numbers which are not greater than R and are divisible by prime factors of N.
- Suppose that the value is y. So, exactly y natural numbers not greater than R have at least a single common divisor with N.
- So, these y numbers can not be relatively prime to N.
- Thus, the number of natural number not greater than R which are relatively prime to N will be R – y .
- Now, similarly we need to find out the number of relatively prime numbers of N which are not greater than L-1.
- Then, subtract the result for L-1 from the answer for R.
Below is the implementation of the above approach:Â
C++
// C++ code to count of natural// numbers in range [L, R] which// are relatively prime with NÂ
#include <bits/stdc++.h>using namespace std;#define maxN (long long)1000000000000Â
// container of all the primes// up to sqrt(n)vector<int> prime;Â
// Function to calculate prime// factors of nvoid sieve(long long n){    // run the sieve of Eratosthenes    bool check[1000007] = { 0 };    long long i, j;Â
    // 0(false) means prime,    // 1(true) means not prime    check[0] = 1, check[1] = 1,    check[2] = 0;Â
    // no even number is    // prime except for 2    for (i = 4; i <= n; i += 2)        check[i] = true;Â
    for (i = 3; i * i <= n; i += 2)        if (!check[i]) {Â
            // all the multiples of each            // each prime numbers are            // non-prime            for (j = i * i; j <= n; j += 2 * i)                check[j] = true;        }Â
    prime.push_back(2);Â
    // get all the primes    // in prime vector    for (int i = 3; i <= n; i += 2)        if (!check[i])            prime.push_back(i);Â
    return;}Â
// Count the number of numbers// up to m which are divisible// by given prime numberslong long count(long long a[],                int n, long long m){    long long parity[3] = { 0 };Â
    // Run from i= 000..0 to i= 111..1    // or check all possible    // subsets of the array    for (int i = 1; i < (1 << n); i++) {        long long mult = 1;        for (int j = 0; j < n; j++)            if (i & (1 << j))                mult *= a[j];Â
        // take the multiplication        // of all the set bitsÂ
        // if the number of set bits        // is odd, then add to the        // number of multiples        parity[__builtin_popcount(i) & 1]            += (m / mult);    }Â
    return parity[1] - parity[0];}Â
// Function calculates all number// not greater than 'm' which are// relatively prime with n.long long countRelPrime(    long long n,    long long m){Â
    long long a[20];    int i = 0, j = 0;    long long pz = prime.size();    while (n != 1 && i < pz) {Â
        // if square of the prime number        // is greater than 'n', it can't        // be a factor of 'n'        if ((long long)prime[i]                * (long long)prime[i]            > n)            break;Â
        // if prime is a factor of        // n then increment count        if (n % prime[i] == 0)            a[j] = (long long)prime[i], j++;Â
        while (n % prime[i] == 0)            n /= prime[i];        i++;    }Â
    if (n != 1)        a[j] = n, j++;    return m - count(a, j, m);}Â
void countRelPrimeInRange(    long long n, long long l,    long long r){    sieve(sqrt(maxN));    long long result        = countRelPrime(n, r)          - countRelPrime(n, l - 1);    cout << result << "\n";}Â
// Driver codeint main(){Â Â Â Â long long N = 7, L = 3, R = 9;Â Â Â Â countRelPrimeInRange(N, L, R);Â
    return 0;} |
Java
// Java code to count of natural// numbers in range [L, R] which// are relatively prime with Nimport java.util.*;Â
class GFG{Â
static int maxN = 100000000;Â
// Container of all the primes// up to sqrt(n)static Vector<Integer> prime = new Vector<Integer>();Â
// Function to calculate prime// factors of nstatic void sieve(int n){         // Run the sieve of Eratosthenes    boolean[] check = new boolean[1000007];    for(int i = 0; i < 1000007; i++)        check[i] = false;Â
    int i, j;Â
    // 0(false) means prime,    // 1(true) means not prime    check[0] = false;    check[1] = true;    check[2] = false;Â
    // No even number is    // prime except for 2    for(i = 4; i <= n; i += 2)        check[i] = true;Â
    for(i = 3; i * i <= n; i += 2)        if (!check[i])        {                         // All the multiples of each            // each prime numbers are            // non-prime            for(j = i * i; j <= n; j += 2 * i)                check[j] = true;        }Â
    prime.add(2);Â
    // Get all the primes    // in prime vector    for(i = 3; i <= n; i += 2)        if (!check[i])            prime.add(i);Â
    return;}Â
static int countSetBits(int n){Â Â Â Â int count = 0;Â Â Â Â while (n > 0) Â Â Â Â {Â Â Â Â Â Â Â Â count += n & 1;Â Â Â Â Â Â Â Â n >>= 1;Â Â Â Â }Â Â Â Â return count;}Â
// Count the number of numbers// up to m which are divisible// by given prime numbersstatic int count(int a[],                 int n, int m){    int[] parity = new int[3];    for(int i = 0; i < 3; i++)        parity[i] = 0;Â
    // Run from i= 000..0 to i= 111..1    // or check all possible    // subsets of the array    for(int i = 1; i < (1 << n); i++)    {        int mult = 1;        for(int j = 0; j < n; j++)            if ((i & (1 << j)) != 0)                mult *= a[j];Â
        // Take the multiplication        // of all the set bitsÂ
        // If the number of set bits        // is odd, then add to the        // number of multiples        parity[countSetBits(i) & 1] += (m / mult);    }    return parity[1] - parity[0];}Â
// Function calculates all number// not greater than 'm' which are// relatively prime with n.static int countRelPrime(int n, int m){    int[] a = new int[20];    int i = 0, j = 0;    int pz = prime.size();         while(n != 1 && i < pz)     {                 // If square of the prime number        // is greater than 'n', it can't        // be a factor of 'n'        if ((int)prime.get(i) *             (int)prime.get(i) > n)            break;Â
        // If prime is a factor of        // n then increment count        if (n % prime.get(i) == 0)         {            a[j] = (int)prime.get(i);            j++;        }Â
        while (n % prime.get(i) == 0)            n /= prime.get(i);                     i++;    }Â
    if (n != 1)    {        a[j] = n;        j++;    }    return m - count(a, j, m);}Â
static void countRelPrimeInRange(int n, int l,                                 int r){    sieve((int)Math.sqrt(maxN));         int result = countRelPrime(n, r) -                  countRelPrime(n, l - 1);                      System.out.println(result);}Â
// Driver codepublic static void main(String[] args){Â Â Â Â int N = 7, L = 3, R = 9;Â Â Â Â Â Â Â Â Â countRelPrimeInRange(N, L, R);}}Â
// This code is contributed by grand_master |
Python3
# Python3 code to count of natural# numbers in range [L, R] which# are relatively prime with Nfrom math import sqrt, floorÂ
maxN = 1000000000000Â
# Container of all the primes# up to sqrt(n)prime = []Â
# Function to calculate prime# factors of ndef sieve(n):         # Run the sieve of Eratosthenes    check = [0] * (1000007)    i, j = 0, 0Â
    # 0(false) means prime,    # 1(True) means not prime    check[0] = 1    check[1] = 1    check[2] = 0Â
    # No even number is    # prime except for 2    for i in range(4, n + 1, 2):        check[i] = TrueÂ
    for i in range(3, n + 1, 2):        if i * i > n:            break        if (not check[i]):Â
            # All the multiples of each            # each prime numbers are            # non-prime            for j in range(2 * i, n + 1, 2 * i):                check[j] = TrueÂ
    prime.append(2)Â
    # Get all the primes    # in prime vector    for i in range(3, n + 1, 2):        if (not check[i]):            prime.append(i)Â
    returnÂ
# Count the number of numbers# up to m which are divisible# by given prime numbersdef count(a, n, m):Â Â Â Â Â Â Â Â Â parity = [0] * 3Â
    # Run from i = 000..0 to i = 111..1    # or check all possible    # subsets of the array    for i in range(1, 1 << n):        mult = 1        for j in range(n):            if (i & (1 << j)):                mult *= a[j]Â
        # Take the multiplication        # of all the set bitsÂ
        # If the number of set bits        # is odd, then add to the        # number of multiples        parity[bin(i).count('1') & 1] += (m // mult)Â
    return parity[1] - parity[0]Â
# Function calculates all number# not greater than 'm' which are# relatively prime with n.def countRelPrime(n, m):Â
    a = [0] * 20    i = 0    j = 0    pz = len(prime)    while (n != 1 and i < pz):Â
        # If square of the prime number        # is greater than 'n', it can't        # be a factor of 'n'        if (prime[i] * prime[i] > n):            breakÂ
        # If prime is a factor of        # n then increment count        if (n % prime[i] == 0):            a[j] = prime[i]            j += 1Â
        while (n % prime[i] == 0):            n //= prime[i]        i += 1Â
    if (n != 1):        a[j] = n        j += 1    return m - count(a, j, m)Â
def countRelPrimeInRange(n, l, r):Â Â Â Â Â Â Â Â Â sieve(floor(sqrt(maxN)))Â Â Â Â result = (countRelPrime(n, r) -Â Â Â Â Â Â Â Â Â Â Â Â Â Â countRelPrime(n, l - 1))Â Â Â Â print(result)Â
# Driver codeif __name__ == '__main__':Â Â Â Â Â Â Â Â Â N = 7Â Â Â Â L = 3Â Â Â Â R = 9Â Â Â Â Â Â Â Â Â countRelPrimeInRange(N, L, R)Â
# This code is contributed by mohit kumar 29 |
C#
// C# code to count of natural// numbers in range [L, R] which// are relatively prime with Nusing System;using System.Collections.Generic;Â
class GFG{Â Â Â Â Â static int maxN = 100000000;Â
// Container of all the primes// up to sqrt(n)static List<int> prime = new List<int>();  // Function to calculate prime// factors of nstatic void sieve(int n){         // Run the sieve of Eratosthenes    bool[] check = new bool[1000007];    for(int I = 0; I < 1000007; I++)        check[I] = false;      int i, j;      // 0(false) means prime,    // 1(true) means not prime    check[0] = false;    check[1] = true;    check[2] = false;      // No even number is    // prime except for 2    for(i = 4; i <= n; i += 2)        check[i] = true;      for(i = 3; i * i <= n; i += 2)        if (!check[i])        {                         // All the multiples of each            // each prime numbers are            // non-prime            for(j = i * i; j <= n; j += 2 * i)                check[j] = true;        }      prime.Add(2);         // Get all the primes    // in prime vector    for(i = 3; i <= n; i += 2)        if (!check[i])            prime.Add(i);      return;}  static int countSetBits(int n){    int count = 0;         while (n > 0)     {        count += n & 1;        n >>= 1;    }    return count;}  // Count the number of numbers// up to m which are divisible// by given prime numbersstatic int count(int[] a, int n, int m){    int[] parity = new int[3];    for(int i = 0; i < 3; i++)        parity[i] = 0;      // Run from i= 000..0 to i= 111..1    // or check all possible    // subsets of the array    for(int i = 1; i < (1 << n); i++)    {        int mult = 1;        for(int j = 0; j < n; j++)            if ((i & (1 << j)) != 0)                mult *= a[j];          // Take the multiplication        // of all the set bits          // If the number of set bits        // is odd, then add to the        // number of multiples        parity[countSetBits(i) & 1] += (m / mult);    }    return parity[1] - parity[0];}  // Function calculates all number// not greater than 'm' which are// relatively prime with n.static int countRelPrime(int n, int m){    int[] a = new int[20];    int i = 0, j = 0;    int pz = prime.Count;         while (n != 1 && i < pz)     {                 // If square of the prime number        // is greater than 'n', it can't        // be a factor of 'n'        if ((int)prime[i] * (int)prime[i] > n)            break;                     // If prime is a factor of        // n then increment count        if (n % prime[i] == 0)         {            a[j] = (int)prime[i];            j++;        }          while (n % prime[i] == 0)            n /= prime[i];                      i++;    }      if (n != 1)    {        a[j] = n;        j++;    }    return m - count(a, j, m);}  static void countRelPrimeInRange(int n, int l,                                 int r){    sieve((int)Math.Sqrt(maxN));          int result = countRelPrime(n, r) -                  countRelPrime(n, l - 1);                       Console.WriteLine(result);}Â
// Driver Codestatic void Main() {Â Â Â Â int N = 7, L = 3, R = 9;Â Â Â Â Â Â Â Â Â countRelPrimeInRange(N, L, R);}}Â
// This code is contributed by divyeshrabadiya07 |
Javascript
<script>Â
// Javascript code to count of natural// numbers in range [L, R] which// are relatively prime with Nlet maxN = 100000000;Â
// Container of all the primes// up to sqrt(n)let prime = [];Â
// Function to calculate prime// factors of nfunction sieve(n){         // Run the sieve of Eratosthenes    let check = new Array(1000007);    for(let i = 0; i < 1000007; i++)        check[i] = false;      let i, j;      // 0(false) means prime,    // 1(true) means not prime    check[0] = false;    check[1] = true;    check[2] = false;      // No even number is    // prime except for 2    for(i = 4; i <= n; i += 2)        check[i] = true;      for(i = 3; i * i <= n; i += 2)        if (!check[i])        {                         // All the multiples of each            // each prime numbers are            // non-prime            for(j = i * i; j <= n; j += 2 * i)                check[j] = true;        }      prime.push(2);      // Get all the primes    // in prime vector    for(i = 3; i <= n; i += 2)        if (!check[i])            prime.push(i);      return;}Â
function countSetBits(n){Â Â Â Â let count = 0;Â Â Â Â while (n > 0)Â Â Â Â {Â Â Â Â Â Â Â Â count += n & 1;Â Â Â Â Â Â Â Â n >>= 1;Â Â Â Â }Â Â Â Â return count;}Â
// Count the number of numbers// up to m which are divisible// by given prime numbersfunction count(a, n, m){    let parity = new Array(3);    for(let i = 0; i < 3; i++)        parity[i] = 0;      // Run from i= 000..0 to i= 111..1    // or check all possible    // subsets of the array    for(let i = 1; i < (1 << n); i++)    {        let mult = 1;        for(let j = 0; j < n; j++)            if ((i & (1 << j)) != 0)                mult *= a[j];          // Take the multiplication        // of all the set bits          // If the number of set bits        // is odd, then add to the        // number of multiples        parity[countSetBits(i) & 1] += (m / mult);    }    return parity[1] - parity[0];}Â
// Function calculates all number// not greater than 'm' which are// relatively prime with n.function countRelPrime(n, m){    let a = new Array(20);    let i = 0, j = 0;    let pz = prime.length;          while(n != 1 && i < pz)    {                 // If square of the prime number        // is greater than 'n', it can't        // be a factor of 'n'        if (prime[i] *            prime[i] > n)            break;          // If prime is a factor of        // n then increment count        if (n % prime[i] == 0)        {            a[j] = prime[i];            j++;        }          while (n % prime[i] == 0)            n = Math.floor(n/prime[i]);                      i++;    }      if (n != 1)    {        a[j] = n;        j++;    }    return m - count(a, j, m);}Â
function countRelPrimeInRange(n, l, r){Â Â Â Â sieve(Math.floor(Math.sqrt(maxN)));Â Â Â Â Â Â Â Â Â Â let result = countRelPrime(n, r) -Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â countRelPrime(n, l - 1);Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â document.write(result);}Â
// Driver codelet N = 7, L = 3, R = 9;Â
countRelPrimeInRange(N, L, R);Â
// This code is contributed by unknown2108Â
</script> |
Output:Â
6
Â
Time Complexity: O(2^N * log(R))
Auxiliary Space: O(N + maxN)
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



