Difference between revisions of "Calculate the greatest common denominator"

From CodeCodex

(put into subcategory)
m (Added haskell solution)
 
Line 1: Line 1:
 +
=== Haskell ===
 +
<pre>
 +
gcd n1 n2
 +
</pre>
 +
For example:
 +
<pre>
 +
Prelude> gcd 10 15
 +
5
 +
</pre>
 +
 
===PHP===
 
===PHP===
 
The Greatest Common Denominator of two large numbers, using BCMath functions.
 
The Greatest Common Denominator of two large numbers, using BCMath functions.

Latest revision as of 16:26, 10 August 2012

Haskell[edit]

gcd n1 n2

For example:

Prelude> gcd 10 15
5

PHP[edit]

The Greatest Common Denominator of two large numbers, using BCMath functions. Please read the PHP manual for BCMath requirements.

It works even for those who cannot have GMP support in their PHP distribution, for instance due to the web host policy.

// You can see a demo here:
// http://www.freephpcalculator.tk/
// License: free to do whatever you want with the code
// even using it
function bcgcd ($value1, $value2) {
	
	if ($value1 < $value2)
	// Swap $value1 and $value2
	{
		$temp = $value1;
		$value1 = $value2;
		$value2 = $temp;
	}

	// We use the Euclid's algorithm
	// for finding the Greatest Common Denominator (GCD)
	$mod = 1;
	while ($mod != 0)
	{
		$mod = bcmod ($value1, $value2);
		$value1 = $value2;
		$value2 = $mod;
	}
	return $value1;

}