Skip to content

Instantly share code, notes, and snippets.

@Kush1101
Created May 18, 2020 12:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kush1101/6ac3d4619d5ca87efe2cdba0c908f0e4 to your computer and use it in GitHub Desktop.
Save Kush1101/6ac3d4619d5ca87efe2cdba0c908f0e4 to your computer and use it in GitHub Desktop.
"""
Problem 37 on project Euler
https://projecteuler.net/problem=37
"""
"""
Note: This code takes about 2 seconds to execute. You ca reduce this time by adapting to
faster methods of checking if a number is prime or not like the Seive method.
But this code is intended to be beginner friendly so I have used the simple way to check for primes.
"""
def isprime(n): # checking if prime
if n==1:
return False
if n!=2 and n%2==0:
return False
for i in range(3,int(math.sqrt(n)+1),2):
if n%i==0:
return False
return True
def truncated(n): # returns a list of truncated n
s = str(n)
l = []
l.append(int(s[:]))
for i in range(1,len(s)):
l.append(int(s[i:]))
l.append(int(s[:-i]))
return l
primes =[] # generating a list of 2 digit primes
for i in range(100,1000): # to validate the numbers so
if isprime(i): #loop will check only a few numbers
primes.append(str(i))
"""
You can significantly reduce the numbers which you will ceheck by the following approach.
A number will be truncatable prime iff the first and last two digits of the number are also prime.
So I wrote a function "validate" which checks for the same and also if the first and last digit of a number is prime or not.
This shall reduce the numbers that we will check and thus optimize the code a lot.
"""
def validate(n): # if the first two or last two digits of
if len(str(n))>3: # n are not prime we will not check it
if str(n)[-3:] not in primes:
return False
if str(n)[:3] not in primes:
return False
if int(str(n)[-1])%2==0: #if first digit of
return False # n is even we will not check it
return True
a=time.time()
c=0 #count variable
s=0 #sum
i=11
while c!=11:
if validate(i):
l=truncated(i)
l1 = list(map(isprime,l))
if all(l1):
print(i)
s+=i
c+=1
i+=2
print("sum = ",s)
print(time.time()-a)
#sum=748317
#time = 2.1 seconds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment