Hi everyone. I was trying to solve Pb 35 on Project Euler (http://projecteuler.net/index.php?section=problems&id=35). It essentially asks to write a program to list all circular primes under 1e6. I wrote the program and it works well for the most part. However, in the end it seems not to be able to conduct membership tests properly. For example, it lists 391 as a prime. I have looked it over and over but I can't figure out what's wrong. I will probably also try a new approach, but I want to know why this doesn't work. I am new to programming, so please forgive me if it's a newbie error. I used Python 2.7, the code follows:
def numrotator(pStr):
s=pStr
a = [] # Contains all the rotated integers
b = [] # Contains the rotated integer for one iteration
for i in range(0, len(s)):
for x in range(len(s) - 1, -1, -1): # Rotation algorithm
b.append(s[i-x])
a.append(b)
b = []
a.reverse() # Prime is listed first.
c = []
for i in a: # Convert strings to integers.
p = ''
for l in i:
p += l
p = int(p)
c.append(p)
return c
def pLister():
# Euler's Sieve implementation. Removes multiples of numbers by removing numbers at the positions where the multiples will be.
n = int(raw_input("Num: ")) # Upper range.
s = range(3, n+1, 2) # Only odds are checked..
i = 1
a = len(s) - 1
for l in range(0, a + 1):
a1 = i
j = (l + (s[l]*i))
while (j <= a) and s[l] != 0:
s[j] = 0
i += 1
j = (l + (s[l]*i))
i = a1 + 1 # Avoid double checking. For example, since 3*7 gets removed first, the algorithm skips 7*3.
s = list(set(s))
s.sort()
s.remove(0)
s = [2] + s
return s
s2 = pLister()
s2.sort()
def dConstructor(s1):
d=[]
for i in s1:
i = str(i)
if '2' not in i and '4' not in i and '5' not in i and '6' not in i and '8' not in i and '0' not in i:
d.append(numrotator(i)) # Only numbers without 2,4,5,6,8, or 0 are rotated since numbers
# containing those digits will be composite in at least one rotation.
for i in d:
i.sort()
d.sort()
for i in d: # Here's where I think the problem lies (The entire loop)
for l in i:
if l not in s1:
while i in d:
d.remove(i)
return len(d) + 2 # If the algorithm works as it should, lists containing circular primes would appear as many times as the number of digits in one circular prime.
print dConstructor(s2)