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
PHP Program to Find GCD or HCF of Two Numbers
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.