VOOZH about

URL: https://www.geeksforgeeks.org/dsa/common-prime-factors-of-two-numbers/

⇱ Common prime factors of two numbers - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Common prime factors of two numbers

Last Updated : 11 Jul, 2025

Given two integer and , the task is to find the common prime divisors of these numbers.
Examples: 
 

Input: A = 6, B = 12 
Output: 2 3 
2 and 3 are the only common prime divisors of 6 and 12
Input: A = 4, B = 8 
Output:
 


 


Naive Approach: Iterate from 1 to min(A, B) and check whether i is prime and a factor of both A and B, if yes then display the number.
Efficient Approach is to do following: 
 

  1. Find Greatest Common Divisor (gcd) of the given numbers.
  2. Find prime factors of the GCD.


Efficient Approach for multiple queries: The above solution can be further optimized if there are multiple queries for common factors. The idea is based on Prime Factorization using Sieve O(log n) for multiple queries.
Below is the implementation of the above approach: 
 


Output: 
2 3

 
Comment