DEV Community

Sharmin Shanta
Sharmin Shanta

Posted on

1

Find out the GCD(Greatest Common Divisor) of the given two numbers in PHP.

It's a manual process to find out the GCD of given two numbers that we've learned in our childhood in general mathematics on standard 2/3.

function getGCD($num1, $num2) {

    if ($num1 == 0 || $num2 == 0)
        return false;

    $divisor = $num1;
    $dividend = $num2;

    if ($num1 > $num2) {
        $divisor = $num2;
        $dividend = $num1;
    }

    $remainder = $dividend % $divisor;
    $quotient = $dividend / $divisor;

    if ($remainder !== 0) {
        $result = $remainder;
    } else {
        $result = $quotient;
    }

    return $result;
}

print_r(getGCD(12, 16)); // Output: 4
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay