PHP Program - Find GCD of Two Numbers
GCD stands for Greatest Common Divisor. The GCD of two numbers is the largest number that divides both of them.
For example - GCD of 20 and 25 is 5, and GCD of 50 and 100 is 50.
Method 1: Using For Loop to find GCD of two numbers
In the example below, for loop is used to iterate the variable i from 1 to the smaller number. If both numbers are divisible by i, then it modifies the GCD and finally gives the GCD of two numbers.
<?php $x = 50; $y = 100; if ($x > $y) { $temp = $x; $x = $y; $y = $temp; } for($i = 1; $i < ($x+1); $i++) { if ($x%$i == 0 and $y%$i == 0) $gcd = $i; } echo "GCD of $x and $y is: $gcd"; ?>
The above code will give the following output:
GCD of 50 and 100 is: 50
Method 2: Using While Loop to find GCD of two numbers
In the example below, larger number is replaced by a number which is calculated by subtracting the smaller number from the larger number. The process is continued until the two numbers become equal which will be GCD of two numbers.
<?php $p = $x = 20; $q = $y = 25; while ($x != $y) { if ($x > $y) $x = $x - $y; else $y = $y - $x; } echo "GCD of $p and $q is: $x"; ?>
The above code will give the following output:
GCD of 20 and 25 is: 5
Method 3: Using the recursive function to find GCD of two numbers
In the example below, recursive function is used. In this method, instead of using subtraction operator(as in above example), modulo operator is used. This method is also known as Euclidean algorithm.
<?php function gcd($x, $y) { if ($y == 0) return $x; return gcd($y, $x%$y); } $x = 250; $y = 475; echo "GCD of $x and $y is: ".gcd($x,$y); ?>
The above code will give the following output:
GCD of 250 and 475 is: 25
Recommended Pages
- PHP Program - To Check Prime Number
- PHP Program - Bubble Sort
- PHP Program - Selection Sort
- PHP Program - Maximum Subarray Sum
- PHP Program - Reverse digits of a given Integer
- PHP - Swap two numbers
- PHP Program - Fibonacci Sequence
- PHP Program - Insertion Sort
- PHP Program - Find Factorial of a Number
- PHP Program - Find HCF of Two Numbers
- PHP Program - Merge Sort
- PHP Program - Shell Sort
- Stack in PHP
- Queue in PHP
- PHP Program - Find LCM of Two Numbers
- PHP Program - To Check Whether a Number is Palindrome or Not
- PHP Program - To Check Whether a String is Palindrome or Not
- PHP Program - Heap Sort
- PHP Program - Quick Sort
- PHP - Swap Two Numbers without using Temporary Variable