#!/usr/bin/perl

# Get the numberator and demoninator from the user

print "\n Numerator? ";
$p = <STDIN>;
chomp($p);

print "\n Demoninator? ";
$q = <STDIN>;
chomp($q);

# Find the gcf of the numerator and demoninator

$l = gcf($p,$q);

# $l is now the GCF of $p and $q
# Now we let p/q = w + n/d (whole + numerator / denominator)

$w = int($p / $q);
$n = ($p % $q) / $l;
$d = $q / $l;

# Prints out the results.  There are three cases-
# there is the whole part, the fraction part, and both.
# This distinguishes between the three and prints out
# the answer accordingly.

if($w == 0) {
  print "\n$p/$q, in least terms, is $n/$d.\n";
}

elsif($n == 0) {
  print "\n$p/$q, in least terms, is $w.\n";
}

else {
  print "\n$p/$q, in least terms, is $w + $n/$d.\n\n";
}

% This gcf function is Euler's function for calculating the gcf
% of two numbers: gcf(x,y) = gcf(y,x mod y), and gcf (x,0) = x
%    i.e.  gcf (24,10) = gcf (10,4)
%                      = gcf (4,2)
%                      = gcf (2,0)
%                      = 2

sub gcf {
  my($x,$y) = @_;
  if ($y == 0) {
    return $x;
  } else {
    $z = $x % $y;
    lcm($y, $z)
  }
}
