/*
###########################################################################
This function returns the GCD (Greatest Common Divisor) for any two
integer strings. The numerical signs of the numbers are ignored.
Arbitrary-precision arithmetic is used, so the integers should be given
as strings, like '1234', so as not to be mistaken for standard floating-
point values.
ARGUMENTS:
($IntAStr, $IntBStr) = Two integers (A, B) as strings.
ERRORS:
FALSE is returned if either argument is non-numeric.
NO DEPENDENCIES
###########################################################################
*/
function BC_GCD ($IntAStr, $IntBStr)
{
// Read integer string arguments.
$A = trim($IntAStr);
$B = trim($IntBStr);
// Error if either (A, B) argument is non-numeric.
if (!Is_Numeric($A) or !Is_Numeric($B)) {return FALSE;}
// Work with absolute values.
$A = Str_Replace('-', '', Str_Replace('+', '', $A));
$B = Str_Replace('-', '', Str_Replace('+', '', $B));
/* Truncate any non-integer to an integer value WITHOUT rounding.
This means that anything following the decimal point will
simply be ignored and lost without rounding the integer part.
*/
$A = bcAdd($A,0); $B = bcAdd($B,0);
// Return 1 if either argument equates to zero.
if (bcComp($A,0) == 0 or bcComp($B,0) == 0) {return 1;}
// if (A < B), then swap (A,B) values to ensure that B >= A initially.
if (bcComp($B,$A) < 0) {$x=$B; $B=$A; $GCD=$x;} else {$GCD=$A;}
// Compute the GCD of the initial (A, B) arguments.
while ($B <> 0) {$x=$B; $B=bcMod($GCD, $B); $GCD=$x;}
return $GCD; // Done when (B == 0).
} // End of BC_GCD (...)