Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Find the sum of all Truncatable primes below N in Python
A truncatable prime is a prime number that remains prime when digits are successively removed from either the left (left-truncatable) or right (right-truncatable) side. A number must be both left-truncatable and right-truncatable to be considered truncatable. For example, 3797 is truncatable because 3797, 797, 97, 7 (left truncation) and 3797, 379, 37, 3 (right truncation) are all prime numbers.
Algorithm
We use the Sieve of Eratosthenes to precompute all primes, then check each number for truncatability ?
- Generate all primes up to a reasonable limit using the sieve
- For each prime number, check if it's left-truncatable and right-truncatable
- Sum all valid truncatable primes below N
Implementation
def sieve_of_eratosthenes(limit):
"""Generate all prime numbers up to limit using Sieve of Eratosthenes"""
prime = [True] * limit
prime[0] = prime[1] = False
for i in range(2, int(limit**0.5) + 1):
if prime[i]:
for j in range(i*i, limit, i):
prime[j] = False
return prime
def is_truncatable_prime(num, prime_list):
"""Check if a number is a truncatable prime"""
if not prime_list[num]:
return False
# Convert to string for easier manipulation
num_str = str(num)
# Check left truncation (remove digits from left)
for i in range(len(num_str)):
truncated = int(num_str[i:])
if not prime_list[truncated]:
return False
# Check right truncation (remove digits from right)
for i in range(len(num_str), 0, -1):
truncated = int(num_str[:i])
if not prime_list[truncated]:
return False
return True
def sum_truncatable_primes(n):
"""Find sum of all truncatable primes below n"""
# Use a reasonable upper limit for sieve
limit = max(n, 1000000)
prime_list = sieve_of_eratosthenes(limit)
total_sum = 0
# Check each number from 2 to n-1
for num in range(2, n):
if is_truncatable_prime(num, prime_list):
total_sum += num
return total_sum
# Example usage
n = 55
result = sum_truncatable_primes(n)
print(f"Sum of truncatable primes below {n}: {result}")
# Let's also show the individual truncatable primes
def find_truncatable_primes(n):
"""Find all truncatable primes below n"""
limit = max(n, 1000000)
prime_list = sieve_of_eratosthenes(limit)
truncatable_primes = []
for num in range(2, n):
if is_truncatable_prime(num, prime_list):
truncatable_primes.append(num)
return truncatable_primes
primes = find_truncatable_primes(55)
print(f"Truncatable primes below 55: {primes}")
print(f"Sum: {sum(primes)}")
Sum of truncatable primes below 55: 130 Truncatable primes below 55: [2, 3, 5, 7, 23, 37, 53] Sum: 130
How It Works
The algorithm works in three main steps ?
- Sieve Generation: Creates a boolean array marking all prime numbers up to the limit
- Truncation Check: For each candidate number, removes digits from both ends and verifies all resulting numbers are prime
- Sum Calculation: Adds all valid truncatable primes below the given limit
Example Verification
Let's verify that 23 is truncatable ?
# Check if 23 is truncatable
number = 23
print(f"Checking if {number} is truncatable:")
# Left truncation: 23 ? 3
print("Left truncation: 23 ? 3")
print(f"23 is prime: True")
print(f"3 is prime: True")
# Right truncation: 23 ? 2
print("Right truncation: 23 ? 2")
print(f"23 is prime: True")
print(f"2 is prime: True")
print(f"Therefore, {number} is truncatable!")
Checking if 23 is truncatable: Left truncation: 23 ? 3 23 is prime: True 3 is prime: True Right truncation: 23 ? 2 23 is prime: True 2 is prime: True Therefore, 23 is truncatable!
Conclusion
Truncatable primes are rare numbers that maintain primality when digits are removed from either end. Using the Sieve of Eratosthenes for efficient prime checking, we can find all truncatable primes below any given limit and calculate their sum.
