📘 Reducing a fraction using Perl 6

📘 Reducing a fraction using Raku

N. B. Perl 6 has been renamed to Raku. Click to read more.


Compose a fraction from the two given integers—numerator and denominator—and reduce it to lowest terms.

5/15 and 16/280 are examples of fractions that can be reduced. The final results of this task are 1/3 and 2/35. Generally, the algorithm of reducing a fraction requires searching for the greatest common divisor, and then dividing both numerator and denominator by that number.

In Perl 6, there is a built-in operator gcd that returns the greatest common divisor, so you can use it to solve the task (notice that gcd is used as an operator, not a function):

my $a = 16;
my $b = 280;

my $gcd = $a gcd $b;
say $a/$gcd; # 2
say $b/$gcd; # 35

That is a classical solution, but Perl 6 offers something much more magical—the Rational data type Rat.

my Rat $r = $a/$b;
say $r.numerator;   # 2
say $r.denominator; # 35

The Rat value keeps its parts as two integers, which are accessible via the numerator and denominator methods. The perl method formats the Rat number in the following way:

say $r.perl;        # <2/35>

Leave a Reply

Your email address will not be published. Required fields are marked *

Retype the CAPTCHA code from the image
Change the CAPTCHA codeSpeak the CAPTCHA code