## Perl Weekly Challenge 223: Count Primes

These are some answers to the Week 223, task 1, of the Perl Weekly Challenge organized by Mohammad S. Anwar.

*Spoiler Alert:* This weekly challenge deadline is due in a few days from now (on July 2, 2023 at 23:59). This blog post offers some solutions to this challenge. Please don’t read on if you intend to complete the challenge on your own.

## Task 1: Count Primes

*You are given a positive integer, $n.*

*Write a script to find the total count of primes less than or equal to the given integer.*

*Example 1*

```
Input: $n = 10
Output: 4
Since there are 4 primes (2,3,5,7) less than or equal to 10.
```

*Example 2*

```
Input: $n = 1
Output: 0
```

*Example 3*

```
Input: $n = 20
Output: 8
Since there are 8 primes (2,3,5,7,11,13,17,19) less than or equal to 20.
```

### Count Primes in Raku

Raku has the build-in is-prime routine, implementing the very fast probabilistic Miller-Rabin test for primality. So we just need to test each integer in the `1..$n`

range and count those that are prime.

```
sub count-primes ($n) {
return ((1..$n).grep({.is-prime})).elems;
}
for 10, 1, 20 -> $test {
say $test.fmt("%-3d => "), count-primes $test;
}
```

This program displays the following output:

```
$ raku ./count-primes.raku
10 => 4
1 => 0
20 => 8
```

### Count Primes in Perl

This is a port to Perl of the Raku program above. Since Perl doesn't have an `is-prime`

built-in routine, we implement our own `is_prime`

subroutine.

```
use strict;
use warnings;
use feature 'say';
sub is_prime {
my $in = shift;
for my $i (2..sqrt $in) {
return 0 if $in % $i == 0;
}
return 1;
}
sub count_primes {
my $n = shift;
return scalar grep {is_prime $_} 2..$n;
}
for my $test (10, 1, 20) {
printf "%-3d => %d\n", $test, count_primes $test;
}
```

This program displays the following output:

```
$ perl ./count-primes.pl
10 => 4
1 => 0
20 => 8
```

## Wrapping up

The next week Perl Weekly Challenge will start soon. If you want to participate in this challenge, please check https://perlweeklychallenge.org/ and make sure you answer the challenge before 23:59 BST (British summer time) on July 9, 2023. And, please, also spread the word about the Perl Weekly Challenge if you can.

## Leave a comment