Project Euler 37 - Truncatable Primes
Official link: https://projecteuler.net/problem=37
Thought Process
For problems like this one there are usually 2 approaches I take
Go through numbers and check if the condition is true
Build up numbers with the correct condition
I opted for the second one
First I build up all right to left truncatable primes, the way I do this is to use a stack
I begin by having a stack with [2,3,5,7] because the last digit must always be prime
I pop off the first element of the stack and call it curr
I begin to append [1,3,5,7,9] to the back of curr because primes must end in odd numbers, then using my is_prime function I check if the new number is a prime
if it is I append it to the stack, and I continue this till the stack is empty
I then build up all left to right truncatable primes, I again use a stack
I begin by having a stack with [2,3,5,7] because the last digit must always be prime
I pop off the first element of the stack and call it curr
I begin to append [1,2,3,4,5,6,7,8,9] to the front of curr, then using my is_prime function I check if the new number is a prime
If it is I append it to the stack, and I continue this till the stack is empty
One thing to note is this one produces way more numbers, so I only append numbers to the the stack if they are less than the maximum of the right to left truncatable primes
Now I have 2 lists, containing all the right to left truncatable primes and left to right truncatable primes, I take the intersection of the set of both lists, because this implies that the number is both left to right and right to left truncatable and if the number is < 10^6, I add it to a running total
Interactive Code
Input an integer (yourinput)
Code will output the sum of all truncatable primes < yourinput