**10 years, 5 months ago**. Due to the rapidly evolving world of technology, some concepts may no longer be applicable.

For many people the mere mention of fractions elicits a wince, and while these lovely math constructs played a notable role in our early years of math, they are reasonably simple entities. While most humans revisit fractions over many years and often still fail to grasp the concept, for a computer, the elementary operations with fractions (addition, subtraction, multiplication, division, and the necessary greatest common factor (GCF) and lowest common multiple (LCM)) can be coded in just a few lines.

While by no means a perfect class (quite possibly a rather poorly coded class), the following provides some basic functions necessary for working with fractions.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | <?php class frac{ public $d; public $n; public function __construct($num, $den) { $this->n = $num; $this->d = $den; } public function gcf($n1, $n2){ if ($n2>$n1){ $tmp = $n1; $n1=$n2; $n2=$tmp; } do{ $rem = $n1 % $n2; $n1 = $n2; $n2 = $rem; }while($rem!=0); return $n1; } public function lcm($n1, $n2){ return $n1*($n2/frac::gcf($n1,$n2)); } public function reduce (){ $g = $this->gcf($this->n,$this->d); $this->n /= $g; $this->d /= $g; } public function multiply (frac $n1, frac $n2){ $f = new frac($n1->n*$n2->n,$n1->d*$n2->d); $f->reduce(); return $f; } public function divide (frac $n1, frac $n2){ return frac::multiply($n1, new frac($n2->d,$n2->n)); } public function add (frac $n1, frac $n2){ $g = frac::lcm($n1->d,$n2->d); $f= new frac($n1->n*($g/$n1->d)+$n2->n*($g/$n2->d),$g); $f->reduce(); return $f; } public function subtract (frac $n1, frac $n2){ return frac::add($n1, new frac(-1*$n2->n,$n2->d)); } public function display(){ return $this->n . "/" . $this->d; } } ?> |

Examples of use:

1/3 + 1/2:

1 2 3 4 5 6 | <?php $f1 = new frac(1,3); $f2 = new frac(1,2); $ans = frac::add($f1,$f2); echo $ans->display(); ?> |

1/8 * 2/5

1 2 3 4 5 6 | <?php $f1 = new frac(1,8); $f2 = new frac(2,5); $ans = frac::multiply($f1,$f2); echo $ans->display(); ?> |

The `gcf`

function uses Euclid’s algorithm, and the `lcm`

function (used to find the common denominator) calls the `gcf`

function.

Given the significant disparity between the ease with which a computer can ‘learn’ fractions, and the difficulty encountered by most students, perhaps it is time to consider teaching fractions as a series of concrete steps – an algorithm – instead of the current method. (Granted, most current methods do provide a method for arriving at an answer, but especially for the determination of the lowest common denominator (or reducing fractions), a procedural methodology (e.g. prime factoring, Euclid’s method, etc) is rarely given.)