📘 Testing prime numbers using Perl 6

📘 Testing prime numbers using Raku

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

Decide if the given number is a prime number.

Prime numbers are those that can be divided only by 1, and by themselves.

Perl 6 provides built-in support, using the is-primeroutine, for checking if the number is prime. There are two ways of using it.

First, as a built-in function:

say 'Prime' if is-prime(17);

Second, as a method on an object of the Inttype:

my $n = 15;
say $n.is-prime
    ?? "$n is prime"
    !! "$n is not prime"

Here, the ternary operator ??… !! is used. This code prints either of the strings, depending on the result of calling $n.is-prime:

17 is prime
15 is not prime

Notice that the is-prime routine contains a hyphen in its name, which is a valid character for identifier names in Perl 6.

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