Greatest Common Divisor (GCD) of Numbers (A, B)
and / or
Reduction of Fraction   (A / B)  to  (a / b)

The (A/B) arguments may be integers or decimal values.  Decimal ratios are converted into integer ratios.
Original
A / B
GCD 1
Reduced
a / b
1 / 1
Decimal
=
1
 

Suggested random (A / B) example fraction to experiment with above:
3010589694936 / 294119081064




When working with several integer fractions, if we wish to retain full precision, the number values we deal with could become very large.  To make it easier to work with a fraction, we may wish to reduce it to its lowest terms.  To do this we need a simple function to compute the GCD of any two given integers.  In this case, the two integers will be the absolute values of the numerator and denominator of the fraction (A/B) we wish to reduce, where (abs(B) > 0).  The following PHP function is the foundation of the above program.

Given two positive integers (A,B), the function will return the greatest common divisor (GCD), or the largest integer that will perfectly divide both (A,B) in common.  The value of the GCD will range anywhere from 1 to a value no greater than the lesser of the two integers.  When GCD=1, it means that the two given integers have no common integer divisor (other than 1, which divides anything).  The GCD never equates to zero.

// This PHP function computes the GCD (Greatest Common Divisor)
// of any two integers (±A, ±B).  The GCD value will always
// equate to a positive integer.

   function bcGCD_AB ($IntAStr, $IntBStr)
{
   $A = trim($IntAStr);   $B = trim($IntBStr);

   $A = bcmul(($A < 0)? "-1":"1", $A);
   $B = bcmul(($B < 0)? "-1":"1", $B);

   if (bccomp($A,$B) > 0) {$w=$A;   $A=$B;   $B=$w;}

   $GCD = $A;

   while ($B != 0)
         {
          $C=$B;     $B=bcmod($GCD, $B);     $GCD=$C;
         }

   return $GCD;
}

Below is a commented version of the GCD function listed above.

// This PHP function computes the GCD (Greatest Common Divisor)
// of any two integers (±A, ±B).  The GCD value will always
// equate to a positive integer.

   function bcGCD_AB ($IntAStr, $IntBStr)
{

// ------------------------------------------
// Read integer arguments as numeric strings.

   $A = trim($IntAStr);   $B = trim($IntBStr);

// --------------------------------
// Work with absolute values of A,B

   $A = bcmul(($A < 0)? "-1":"1", $A);
   $B = bcmul(($B < 0)? "-1":"1", $B);

// ----------------------------------------------
// If A > B, then swap (A,B) values so that A < B

   if (bccomp($A,$B) > 0) {$w=$A;   $A=$B;   $B=$w;}

// ------------------------------------
// Equate 1st approximation of GCD to A

   $GCD = $A;

// ------------------------------------------
// Perform Euclid's algorithm loop until B==0

   while ($B != 0)
         {
          $C=$B;     $B=bcmod($GCD, $B);     $GCD=$C;
         }

   return $GCD;
}


© Jay Tanner - PHP Science Labs - 2017 - v4.5