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.
#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
#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;
}
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.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.