#!/usr/bin/perl

$r = 1;	# Set the remainder to one so the while loop will succeed

# Get the numberator and demoninator from the user

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

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

# First find the LCM of the numerator and demoninator

if ($a < $b) {$c = $a; $a = $b; $b = $c;}

while($b > 0) {
  $c = $a - ($b * int($a / $b));
  $a = $b;
  $b = $c;
}

# $a 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 - ($w * $q)) / $a;
$d = ($q / $a);

# 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";
}
