PHP Common Divisors Program

Beginner
6 min read
Updated: Oct 2026
3 programs
Live preview

What Are Common Divisors?

A positive integer d is a common divisor of a and b when it divides both numbers with remainder 0. The largest common divisor is the GCD (greatest common divisor).

Remember
d is a common divisor of a and b
  ⇔  a % d == 0  and  b % d == 0

Key fact:
  common divisors of (a, b)  =  all divisors of gcd(a, b)

Example: a = 12, b = 18
  gcd = 6
  common divisors = 1, 2, 3, 6
abCommon divisorsGCD
12181, 2, 3, 66
71311
24361, 2, 3, 4, 6, 1212

How to Find Common Divisors in PHP

Four clear steps — then pick a basic loop, a GCD scan, or sqrt pairs.

  1. Take absolute values of a and b (divisors are about magnitude).
  2. Reject the case where both values are 0 (no finite list).
  3. Either scan 1 … min(a, b), or compute gcd and list its divisors.
  4. Collect and print the common divisors (and optionally the GCD).
MethodIdeaTimeBest for
Naive loopTest every i from 1 to min(a, b)O(min)Interviews, small inputs
GCD + divisorsFind g = gcd(a, b), then list divisors of gO(log min + g)Clearer math
GCD + sqrt pairsWalk to √g; collect factor pairsO(log min + √g)Larger GCDs

Pseudocode

Pseudocode
function CommonDivisors(a, b):
    a = abs(a)
    b = abs(b)
    if a == 0 and b == 0:
        reject input

    limit = min(a, b)          // if one is 0, use the other
    if limit == 0:
        limit = max(a, b)

    for i from 1 to limit:
        if a mod i == 0 and b mod i == 0:
            print i

Cheat Sheet

Keep these facts handy while writing the program.

TopicDetail
Testa % d == 0 && b % d == 0
Upper boundScan only to min(|a|, |b|)
GCD shortcutCommon divisors = divisors of gcd(a, b)
Always included1 (unless both are 0)
Largestgcd(a, b) itself
Classic check12, 18 → 1, 2, 3, 6

Live Preview

Enter two integers to see their GCD and every common divisor.

Whole numbers (absolute values used). Tap a chip or type a pair.

Result
a = 12, b = 18
gcd(12, 18) = 6
Common divisors: 1, 2, 3, 6
Count = 4

Worked Walkthrough — a = 12, b = 18

Check every candidate from 1 through min(12, 18) = 12. Keep only values that divide both.

Calculation
i=1  → 12%1==0 and 18%1==0  → keep
i=2  → 12%2==0 and 18%2==0  → keep
i=3  → 12%3==0 and 18%3==0  → keep
i=4  → 12%4==0 but 18%4!=0  → skip
i=5  → skip
i=6  → 12%6==0 and 18%6==0  → keep
i=7..12 → skip

Common divisors: 1, 2, 3, 6
gcd = 6

PHP Programs

Start with the readable loop to min(a, b). Then use GCD plus a divisor scan, and finish with sqrt factor pairs.

Example 1 — Simple Loop

Test every integer from 1 to min(a, b) and collect those that divide both.

php
<?php
function commonDivisorsNaive(int $a, int $b): array
{
    $a = abs($a);
    $b = abs($b);

    if ($a === 0 && $b === 0) {
        return [];
    }

    $limit = min($a, $b);
    if ($limit === 0) {
        $limit = max($a, $b);
    }

    $ans = [];
    for ($i = 1; $i <= $limit; $i++) {
        if ($a % $i === 0 && $b % $i === 0) {
            $ans[] = $i;
        }
    }
    return $ans;
}

$a = 24;
$b = 36;
$list = commonDivisorsNaive($a, $b);
echo "Common divisors of $a and $b are: " . implode(', ', $list) . "\n";

How It Works

  1. Take absolute values with abs() so negative inputs behave like positives.
  2. If both are 0, return an empty array — there is no finite set of common divisors.
  3. Set $limit to the smaller magnitude (or the nonzero value if one input is 0).
  4. For each $i from 1 to $limit, append $i only when both remainders are 0.
  5. For 24 and 36, the kept values are 1, 2, 3, 4, 6, 12.

Example 2 — GCD Method

Compute gcd(a, b), then list every divisor of that GCD.

php
<?php
function gcdNonneg(int $x, int $y): int
{
    while ($y !== 0) {
        $t = $x % $y;
        $x = $y;
        $y = $t;
    }
    return $x;
}

function commonDivisorsViaGcd(int $a, int $b): array
{
    $a = abs($a);
    $b = abs($b);

    if ($a === 0 && $b === 0) {
        return [];
    }

    $g = gcdNonneg($a, $b);
    $ans = [];
    for ($i = 1; $i <= $g; $i++) {
        if ($g % $i === 0) {
            $ans[] = $i;
        }
    }
    return $ans;
}

$a = -12;
$b = 18;
$list = commonDivisorsViaGcd($a, $b);
echo "Common divisors of $a and $b are: " . implode(', ', $list) . "\n";

How It Works

  1. gcdNonneg uses the Euclidean algorithm until the remainder is 0.
  2. For 12 and 18, that yields $g = 6 (signs ignored via abs).
  3. Every common divisor must divide 6, so it is enough to list divisors of $g.
  4. Loop $i from 1 to $g and append when $g % $i === 0.
  5. Result is sorted automatically: 1, 2, 3, 6.

Example 3 — Sqrt Factor Pairs

After GCD, walk only to √g and collect each factor pair — faster for larger GCDs.

php
<?php
function gcdNonneg(int $x, int $y): int
{
    while ($y !== 0) {
        $t = $x % $y;
        $x = $y;
        $y = $t;
    }
    return $x;
}

function commonDivisorsSqrt(int $a, int $b): array
{
    $a = abs($a);
    $b = abs($b);

    if ($a === 0 && $b === 0) {
        return [];
    }

    $g = gcdNonneg($a, $b);
    $small = [];
    $large = [];
    $i = 1;

    while ($i * $i <= $g) {
        if ($g % $i === 0) {
            $small[] = $i;
            $other = intdiv($g, $i);
            if ($other !== $i) {
                $large[] = $other;
            }
        }
        $i++;
    }

    return array_merge($small, array_reverse($large));
}

$a = 24;
$b = 36;
$list = commonDivisorsSqrt($a, $b);
echo "Common divisors of $a and $b are: " . implode(', ', $list) . "\n";

How It Works

  1. Compute $g = gcd(|a|, |b|) as before.
  2. Loop $i while $i * $i <= $g — only up to the square root.
  3. When $i divides $g, push $i into $small and $g / $i into $large (skip duplicates when equal).
  4. Merge $small with array_reverse($large) for ascending order.
  5. Same answer as the full scan, in O(√g) after the GCD.

Edge Cases & Pitfalls

Check these before calling the solution done.

Both 0

No finite list

Reject or return empty. Do not loop forever.

One 0

Use the nonzero value

Common divisors are exactly the divisors of the nonzero number.

Negatives

Take abs()

Positive divisors depend on magnitude, not sign.

Coprime

Only 1

Pairs like 7 and 13 share only 1.

Time and Space Complexity

ProgramTimeExtra space
Naive loop to min(a, b)O(min(a, b))O(1) beyond the answer list
GCD + scan 1…gO(log min + g)O(1) beyond the answer list
GCD + sqrt pairsO(log min + √g)O(1) beyond the answer list

g is gcd(|a|, |b|).

Key Takeaways

  • Definition: d divides both a and b.
  • GCD shortcut: common divisors = all divisors of gcd(a, b).
  • Three loops: naive to min, scan 1…g, or sqrt pairs.
  • Test set: 12, 18 → 1 2 3 6; 7, 13 → 1.

One line: values that divide both numbers — or simply every divisor of their GCD.

Frequently Asked Questions

A positive integer d is a common divisor of a and b when a % d == 0 and b % d == 0. For 12 and 18, the common divisors are 1, 2, 3, and 6.
Loop from 1 to min(a, b) and collect values that divide both, or compute gcd(a, b) and list the divisors of that gcd.
Every common divisor of a and b divides gcd(a, b), and every divisor of gcd(a, b) is a common divisor. So listing divisors of the gcd is enough.
Yes for any pair that is not both zero. The number 1 divides every integer.
The naive loop is O(min(a, b)). Computing gcd is O(log min), then listing its divisors is O(g) with a simple 1..g scan, or O(sqrt(g)) with the pair method.

Next: Composite Number

Check whether a number has more than two positive divisors.

Composite number tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

16 people found this page helpful