Common Factors of Two Numbers in C

Common factors are integers that divide two numbers exactly. For example, the positive common factors of 12 and 18 are 1, 2, 3 and 6.

Display Common Factors of Two Numbers Top ↑

#include <stdio.h>

void common_factors(int first, int second) {
    if (first < 0) {
        first = -first;
    }

    if (second < 0) {
        second = -second;
    }

    if (first == 0 && second == 0) {
        printf("0 and 0 do not have a finite list of common factors.\n");
        return;
    }

    int limit = first < second ? first : second;

    if (limit == 0) {
        limit = first > second ? first : second;
    }

    printf("Common factors: ");

    for (int i = 1; i <= limit; i++) {
        if (first % i == 0 && second % i == 0) {
            printf("%d ", i);
        }
    }

    putchar('\n');
}

int main(void) {
    int first = 12;
    int second = 18;

    common_factors(first, second);
    return 0;
}

Output

Common factors: 1 2 3 6

Read Both Numbers from the User Top ↑

#include <stdio.h>

int main(void) {
    int first;
    int second;

    printf("Enter two integers: ");
    if (scanf("%d %d", &first, &second) != 2) {
        printf("Invalid input.\n");
        return 1;
    }

    if (first < 0) first = -first;
    if (second < 0) second = -second;

    if (first == 0 && second == 0) {
        printf("No finite common-factor list for 0 and 0.\n");
        return 0;
    }

    int limit = first < second ? first : second;

    if (limit == 0) {
        limit = first > second ? first : second;
    }

    for (int i = 1; i <= limit; i++) {
        if (first % i == 0 && second % i == 0) {
            printf("%d ", i);
        }
    }

    putchar('\n');
    return 0;
}

Common Factors vs Highest Common Factor Top ↑

This page lists every positive common factor. If you only need the largest one, use the more efficient Euclidean algorithm on the HCF / GCD page.





plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer