Print the kth common factor of two numbers

Given two numbers x and y, we need to find their kth common factor. Common factors are the numbers that divide both x and y without leaving a remainder.

Syntax

int findKthCommonFactor(int x, int y, int k);

Algorithm

The approach to find the kth common factor is −

  1. Find the smaller of the two numbers (maximum possible common factor)
  2. Iterate from 1 to the smaller number
  3. Check if the current number divides both x and y
  4. Count common factors and return when we reach the kth factor

Example

Let's implement a program to find the kth common factor of two numbers −

#include <stdio.h>

int findKthCommonFactor(int x, int y, int k) {
    int count = 0;
    int limit = (x < y) ? x : y;
    
    for (int i = 1; i <= limit; i++) {
        if (x % i == 0 && y % i == 0) {
            count++;
            if (count == k) {
                return i;
            }
        }
    }
    return -1; // kth common factor doesn't exist
}

int main() {
    int x = 12, y = 18, k = 3;
    
    printf("Numbers: x = %d, y = %d<br>", x, y);
    printf("Finding %d common factor<br>", k);
    
    int result = findKthCommonFactor(x, y, k);
    
    if (result != -1) {
        printf("The %d common factor is: %d<br>", k, result);
    } else {
        printf("The %d common factor does not exist<br>", k);
    }
    
    return 0;
}
Numbers: x = 12, y = 18
Finding 3 common factor
The 3 common factor is: 6

Example with All Common Factors

Here's an enhanced version that displays all common factors −

#include <stdio.h>

int main() {
    int x = 9, y = 18, k = 2;
    int count = 0;
    int limit = (x < y) ? x : y;
    
    printf("Factors of %d: ", x);
    for (int i = 1; i <= x; i++) {
        if (x % i == 0) {
            printf("%d ", i);
        }
    }
    
    printf("\nFactors of %d: ", y);
    for (int i = 1; i <= y; i++) {
        if (y % i == 0) {
            printf("%d ", i);
        }
    }
    
    printf("\nCommon factors: ");
    for (int i = 1; i <= limit; i++) {
        if (x % i == 0 && y % i == 0) {
            count++;
            printf("%d ", i);
            if (count == k) {
                printf("\nThe %d common factor is: %d<br>", k, i);
            }
        }
    }
    
    return 0;
}
Factors of 9: 1 3 9 
Factors of 18: 1 2 3 6 9 18 
Common factors: 1 3 9 
The 2 common factor is: 3

Key Points

  • Common factors are always less than or equal to the smaller of the two numbers
  • The function returns -1 if the kth common factor doesn't exist
  • Time complexity is O(min(x, y)) and space complexity is O(1)

Conclusion

Finding the kth common factor involves iterating through possible divisors and counting those that divide both numbers. This approach efficiently handles cases where the requested factor doesn't exist.

Updated on: 2026-03-15T11:08:22+05:30

382 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements