πŸ“˜ Testing prime numbers using Perl 6

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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s