Count of Numbers Between L and R that are Coprime with P in CPP


In the field of computer programming, finding the count of numbers between a given range that are coprime with a specific number can be a common task. Coprime numbers, also known as relatively prime numbers, are those that have no common factors other than 1. In this piece, we shall delve into finding the coprime numbers count between two given integers, L and R when referring to a particular number P, through the aid of C++ language.

Syntax

We'll commence by outlining the syntax of the approach we will be utilizing in the succeeding code examples −

int countCoprimes(int L, int R, int P);

Algorithm

The algorithm we will be using to calculate the count of coprime numbers is as follows −

  • Initialize a variable count to 0, which will store the count of coprime numbers.

  • Iterate through each number, num, starting from L up to R.

  • For each num, check if it is coprime with P.

  • If num and P are coprime, increment the count by 1.

  • Return the final value of count.

Approach 1: Naive Approach

The first approach we will discuss is the naive approach. In order to verify coprimality with P using the Euclidean algorithm, this method entails examining every number within a specified range through iteration.

Example

#include <iostream>

int countCoprimes(int L, int R, int P) {
   int count = 0;
   for (int num = L; num <= R; num++) {
      int a = num;
      int b = P;
      while (b != 0) {
         int temp = b;
         b = a % b;
         a = temp;
      }
      if (a == 1)
         count++;
   }
   return count;
}

int main() {
   int L = 1; // Set the starting range value
   int R = 100; // Set the ending range value
   int P = 7; // Set the value of P
   
   int result = countCoprimes(L, R, P);
    
   std::cout << "Count of numbers between " << L << " and " << R << " coprime with " << P << ": " << result << std::endl;
   
   return 0;
}

Output

Count of numbers between 1 and 100 coprime with 7: 86

Explanation

The countCoprimes function takes three parameters: L (the starting range value), R (the ending range value), and P (the value of P).

Inside the countCoprimes function, we initialize a variable count to 0, which will store the count of coprime numbers.

The for loop iterates through each number, num, starting from L up to R.

Inside the loop, we initialize variables a and b to num and P, respectively.

We use the Euclidean algorithm in the while loop to find the greatest common divisor (GCD) of a and b by repeatedly swapping and performing modulo operations.

If the GCD (stored in a) is equal to 1, it means num and P are coprime. In that case, we increment the count variable.

We finalize our count value by returning it once we have meticulously iterated through all numbers.

The main function thoughtfully assigns suitable values for L, R and P variables.

We then call the countCoprimes function with the provided values and store the result in the result variable.

Finally, we display the result, which is the count of numbers between L and R that are coprime with P.

Approach 2: Prime Factorization

This strategy involves utilizing P's prime factorization to calculate the count of coprime integers that fall between L and R in a precise manner.

Example

#include <iostream>
#include <unordered_set>

int countCoprimes(int L, int R, int P) {
   std::unordered_set<int> factors;
   int tempP = P;

   for (int i = 2; i * i <= tempP; i++) {
      while (tempP % i == 0) {
         factors.insert(i);
         tempP /= i;
      }
   }

   if (tempP > 1)
      factors.insert(tempP);

   int count = 0;
   for (int num = L; num <= R; num++) {
      bool isCoprime = true;
      for (int factor : factors) {
         if (num % factor == 0) {
            isCoprime = false;
            break;
         }
      }
      if (isCoprime)
         count++;
   }

   return count;
}

int main() {
   int L = 1; // Set the starting range value
   int R = 100; // Set the ending range value
   int P = 7; // Set the value of P

   int result = countCoprimes(L, R, P);

   std::cout << "Count of numbers between " << L << " and " << R << " coprime with " << P << ": " << result << std::endl;

   return 0;
}

Output

Count of numbers between 1 and 100 coprime with 7: 86

Explanation

The countCoprimes function takes three parameters: L (the starting range value), R (the ending range value), and P (the value of P).

We create an unordered set of factors to store the prime factors of P. We initialize a temporary variable tempP to P.

We iterate from 2 to the square root of tempP. If temp P is divisible by i, we add i to the set factors and divide tempP by i until it is no longer divisible by i.

If tempP is greater than 1 after the above loop, it means it is a prime number itself and should be added to factors.

We initialize a variable count to 0, which will store the count of coprime numbers.

We iterate through each number, num, starting from L up to R, and check if it is divisible by any of the factors in the set factors. If it is, we mark it as non-coprime.

Upon completing iterations for all numbers, the resultant count is returned as the final value. As for the main function, it initializes L, R and P with specified values.

We then call the countCoprimes function with the provided values and store the result in the result variable.

Finally, we display the result, which is the count of numbers between L and R that are coprime with P.

Conclusion

Calculating co-prime numbers within a designated range L-R and respecting some specific value P is a neat challenge for programmers - but what are the best ways to go about this on a granular code level? As part of this article we've dug into two C++ uses cases that offer real efficiencies when tackling such problems. Firstly there's iteration over all values within that target interval and checking whether those numbers match up as co-primes using the Euclidean algorithm; alternatively there is Euler's phi function method which employs optimization strategies instead. Getting the most out of either method can depend highly on contextual factors like your chosen number and specified interval, yet making smart choices in between both possible approaches can really speed up your program execution overall. For coders looking to add technical finesse and creative problem-solving skills to their repertoires, mastering coprime counting with C++ via these methods could be just what they need.

Updated on: 25-Jul-2023

125 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements