Count common prime factors of two numbers in C++


We are given the two numbers let’s say x and y and the task is to find the common prime factors between two numbers. Common prime factors can be found by firstly calculating the common numbers between two numbers and after that checking from the list of common factors the one which are prime numbers.

For Example

Input − x = 10 y = 20
Output − Common prime factor of two numbers are: 2 5

Explanation − common primes factors between 10 and 20 are 2 and 5 only.

Input − x = 34 y = 12
Output − Common prime factor of two numbers are: 2

Explanation − common primes factors between 34 and 12 are 2.

Approach used in the below program is as follows

  • Input the values of two numbers x and y.

  • Create a function and inside a function

  • Declare a temporary variable that will the greatest common divisor of numbers x and y

  • Create a loop starting from 2 till it’s less than or equals to GCD and increment the i

  • Inside the loop check whether prime[i] && GCD%i = 0 and if this is true

  • Print the value of i

  • Print the result

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
#define MAX 100001
bool prime[MAX];
void SieveOfEratosthenes(){
   // Create a boolean array "prime[0..n]" and initialize
   // all entries are true. A value in prime[i] will
   // finally be false if i is Not a prime, else true.
   memset(prime, true, sizeof(prime));
   // 0 and 1 are not prime numbers
   prime[0] = false;
   prime[1] = false;
   for (int p = 2; p * p <= MAX; p++){
      // If prime[p] is not changed, then it is a prime
      if (prime[p] == true){
         // Updating all multiples of p as non-prime
         for (int i = p * p; i <= MAX; i += p){
            prime[i] = false;
         }
      }
   }
}
// Function to find the common prime numbers
void common_prime(int x, int y){
   // Obtain the GCD of the given numbers
   int g = __gcd(x, y);
   // Find the prime divisors of the g
   for (int i = 2; i <= (g); i++){
      // If i is prime and divisor of g
      if (prime[i] && g % i == 0){
         cout << i << " ";
      }
   }
}
// main code
int main(){
   // Creating the Sieve
   SieveOfEratosthenes();
   int x = 20, y = 30;
   cout<<"Common prime factor of two numbers are: ";
   common_prime(x, y);
   return 0;
}

Output

If we run the above code it will generate the following output −

Common prime factor of two numbers are: 2 5

Updated on: 15-May-2020

208 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements