"The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.\n",
"\n",
"Find the sum of the only eleven primes that are both truncatable from left to right and right to left.\n",
"\n",
"NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Okay, I would say we start with one digit and work ourselves up. I will start with implementing a function that takes all current solutions (with one digit for example) and then tests all possible new solutions (aka all two digit primes) if the can be truncated to the one digit solutions.\n",
"\n",
"This was complicated. Let's formulate it clearer. We write a function that takes a list of numbers and tests whether they are left/right trunctable to another list of numbers."
"Now we simply start with all one digit primes and work our way up using the two functions we have created. On the way up we add the numbers to our result list. For example, 97 is already a valid solution even though it is also the subset of a solution with more digits."
"This are not the eleven numbers we are looking for. The mistake we made is to not differentiate between left truncatable numbers and right truncatable numbers. For example, 397 is truncatable from the left, but not from the right and is still part of a solution. What we want to do is to work up from both directions and then compute the subset. Hence we write to new functions to check for all truncatable numbers from either left or right and then apply the algorithm from above to both of them."
"I added the terminate symbols because this algorithm did not even terminate. This means there are fairly big primes in either direction. We change the approach from bottom up into the other direction. Let's get all primes till a certain value and just check for them. Aka brute force. For this purpose we write a function that takes a number and checks if it is truncatable in both directions."
"s = [p for p in primes_till_10000 if is_truncatable(p, primes_till_10000)]\n",
"print(s)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The one digit numbers are not relevant but this means we got only ten solutions. So we actually have to try all numbers till $10^{6}$. As it turned out we actually have to add one more digit. This is really ugly brute force. I do not like it. But seems like we got a solution."