DEV Community

Simon Green
Simon Green

Posted on

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

Top comments (0)