Open In App

PHP Program to Find GCD or HCF of Two Numbers

Last Updated : 24 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given two numbers, the task is to find the GCD or HCF of two numbers in PHP. GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest positive integer that divides both numbers without leaving a remainder.

Formula to Find GCD

GCD ( a, b ) = [ |a.b| ] / [ lcm(a, b) ]
HCF of factors = Product of the Numbers/ LCM of numbers

Examples:

Input: a = 20, b = 25
Output: 4

Input: a = 40, b = 50
Output: 10

Explanation: The factors of 20 are 1, 2, 4, 5, 10 and 20. The factors of 25 are 1, 5, and 25. Among these factors, 1 and 5 are the common factors of both 20 and 25. The greatest among the common factors is 5.

There are two methods to find the GCD or HCF of two numbers, these are:

We will explore all the above methods along with their basic implementation with the help of examples.

Find GCD or HCF of Two Numbers using for Loop

In this approach, we will iterate a for loop from 1 to till minimum of both numbers. Update GCD when both numbers are divisible.

Syntax:

for ( let i = 1; i < min(a, b); i ++) {
if (a % i === 0 && b % i === 0)
gcd = i;
}

Example:

PHP




<?php
 
function GCD($a, $b) {
    $smallVal = min($a, $b);
    $gcd = 1;
 
    for ($i = 1; $i <= $smallVal; $i++) {
        if ($a % $i === 0 && $b % $i === 0) {
            $gcd = $i;
        }
    }
 
    return $gcd;
}
 
$num1 = 20;
$num2 = 25;
 
echo GCD($num1, $num2);
 
?>


Output

5

Find GCD of Two Numbers using Recursion

In this approach, the recursive function GCD calculates Greatest Common Divisor using the Euclidean algorithm. If “b = 0”, it returns “a”, otherwise, recursively calls with b and remainder of a/b.

Syntax:

function GCD(a, b) {
if ( b === 0 ) {
return a;
}
return GCD(b, a % b);
}

Example: In this example, we are using the above-explained approach.

PHP




<?php
 
function GCD($a, $b) {
    if ($b === 0) {
        return $a;
    }
    return GCD($b, $a % $b);
}
 
$num1 = 28;
$num2 = 35;
 
$result = GCD($num1, $num2);
 
echo $result;
 
?>


Output

7



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads