DEV Community

Simon Green
Simon Green

Posted on

4 2

It's a primathon!

Weekly Challenge 158

Challenge, My solutions

Happy 3rd birthday PWC. As we know, three is a prime number, which is the theme of this weeks challenges.

Two relatively straight forward tasks this week, so not much explanation required. Both tasks use a is_prime method which I took from a previous week. Given an integer, it will true True / False ('1' / undef in Perl) if that number is an integer.

TASK #1 › Additive Primes

Task

Write a script to find out all Additive Primes <= 100. Additive primes are prime numbers for which the sum of their decimal digits are also primes.

My solution

I have a set (hash in Perl) called primes that has the primes found so far. We know that the sum of the digits will never be higher than than the number itself.

I loop from 1 to 100, add the number to the primes set. If the sum of the number is also a prime, I add it to the additive_primes list (array in Perl).

Finally I display the list as output.

Example

$ ./ch-1.py 
2, 3, 5, 7, 11, 23, 29, 41, 43, 47, 61, 67, 83, 89
Enter fullscreen mode Exit fullscreen mode

TASK #2 › First Series Cuban Primes

Task

Write a script to compute first series Cuban Primes <= 1000.

My solution

For this task I have a counter x that starts from one. For each number, I calculate 3x² + 3x + 1 (taken from the wikipedia page). If that number is > 1000, I exit the loop. If that number is a prime, I add it to the cuban_primes list.

Like with the previous task, I end by printing the list. I notice that the example has a full stop at the end. Not sure if this is intentional or not.

Example

$ ./ch-2.py 
7, 19, 37, 61, 127, 271, 331, 397, 547, 631, 919
Enter fullscreen mode Exit fullscreen mode

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay