DEV Community

oldtechaa
oldtechaa

Posted on

Perl Weekly Challenge #223 - Count Primes? I've Never Met the Man

Hello everybody! It's another week with a new Perl Weekly Challenge. This week I'm only doing the first challenge, not because of time, but because the second challenge makes absolutely no sense to me. Perhaps a clarification will come out, but I'm not going to bother at the moment.

This week the challenge is to find the number of primes under the provided number. This is a challenge that really isn't worth rewriting, and so I would recommend using Math::Prime::Util. You have to know when to just trust the professionals and use modules. With the use of M::P::U, we can essentially do the challenge in one line.

use Math::Prime::Util 'primes';
say scalar @{primes(shift)};
Enter fullscreen mode Exit fullscreen mode

primes() returns an array reference, so we have to dereference the array after calling the function. We shift the number that is entered, call primes (which provides an array of the primes under that number), and dereference it and count it to print the answer.

It's that simple! This is a case where I definitely wouldn't recommend writing your own custom prime finder. I'll hopefully see you next week with the next challenge!

Top comments (0)