PHP program to find GCD of two numbers using the while loop and using the for loop
ADVERTISEMENTS
PHP program to find GCD of two numbers using the while loop and using the for loop. There are you will learn how to find the GCD of two numbers using the while loop and using the for loop.
What is the GCD?
The GCD is the largest integer number of two positive integer numbers that can exactly divide both numbers without remaining a remainder.
Let us consider the examples to understand this through PHP programs:
1. PHP program to find the GCD of two numbers using the while loop:
<?php
// PHP program to find GCD of
// two numbers using the while loop
$p = 30;
$q = 20;
while ($p != $q) {
if ($p > $q) {
$p -= $q;
} else {
$q -= $p;
}
}
echo "The GCD number is: " . $p;
?>
Output:
The GCD number is: 10
2. PHP program to find the GCD of two numbers using the for loop:
<?php
// PHP program to find GCD of
// two numbers using the for loop
$p = 30;
$q = 20;
$g = 0;
for ($i = 1; $i <= $p && $i <= $q; ++$i) {
if ($p % $i == 0 && $q % $i == 0) {
$g = $i;
}
}
echo "The GCD number of " . $p . " & " . $q . " is: " . $g;
?>
Output:
The GCD number of 30 & 20 is: 10
Tags:
# write a PHP program to find gcd of two numbers using recursion
# write a PHP program to find gcd of two numbers using functions
# write a PHP program to find lcm of two numbers