VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-kth-common-factor-two-numbers/

⇱ Print the kth common factor of two numbers - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print the kth common factor of two numbers

Last Updated : 9 Jan, 2023

Given three numbers x, y and k, find the k'th common factor of x and y. Print -1 if there are less than k common factors of x and y. 
Examples : 
 

Input : x = 20, y = 24
 k = 3
Output : 4
Common factors are 1, 2, 4, ...

Input : x = 4, y = 24
 k = 2
Output : 2

Input : x = 22, y = 2
 k = 3
Output : -1

We find the smaller of two numbers as common factor cannot be greater than the smaller number. Then we run a loop from 1 to the smaller number. For every number i, we check if it is a common factor. If yes, we increment count of common factors. 
Below is the Implementation : 
 

Time complexity: O(n) where n is smallest among (x,y)
Auxiliary space: O(1)


 

Comment
Article Tags: