def problem35(): """ The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime. There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97. How many circular primes are there below one million? """ count = 1 for i in range(3, 1000000): m = str(i) not_prime = False for d in m: if int(d) % 2 == 0: not_prime = True break if not_prime: continue for i in range(0, len(m)): m = m[1:] + m[0] if not mlib.is_prime(int(m)): not_prime = True break if not not_prime: count += 1 return count
def problem3(): """ The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? """ num = 600851475143 r = int(math.floor(math.sqrt(num))) if r%2 == 0: r += 1 for i in range(r, 0, -2): if num%i == 0 and mlib.is_prime(i): return i
def problem37(): """ 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. Find the sum of the only eleven primes that are both truncatable from left to right and right to left. """ count = 0 n = 10 sum = 0 while count < 11: n += 1 is_cprime = True for d in str(n): # 2 on the edge can be prime if d in "0468": is_cprime = False p = n while p > 0: if not is_cprime or not mlib.is_prime(p): is_cprime = False break p /= 10 p = n while p > 0: if not is_cprime or not mlib.is_prime(p): is_cprime = False break p = p - int(str(p)[0]) * 10 ** (len(str(p)) - 1) if is_cprime: count += 1 sum += n return sum
def problem7(): """ By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6^(th) prime is 13. What is the 10001^(st) prime number? """ val = 1 count = 0 while True: val += 1 if mlib.is_prime(val): count += 1 if count == 10001: return val
def problem41(): # must have < 9 digits, 9-pandigit is div by 9 digits = '12345678' max_p = 0 for i in range(8, 1, -1): gen = mlib.gen_permutation(digits[:i]) while True: try: p = gen.next() if mlib.is_prime(int(p)) and int(p) > max_p: max_p = int(p) except StopIteration: break return max_p
def problem47(): max = 10**6 pmap = [0 for i in range(max)] for i in range(2, int(math.sqrt(max))): if not mlib.is_prime(i): continue k = i while k < len(pmap): pmap[k] += 1 k += i for i in range(10, len(pmap), 4): if pmap[i] == 4: if pmap[i+1] == 4 and pmap[i+2] == 4 and pmap[i+3] == 4: return i if pmap[i-1] == 4 and pmap[i-2] == 4 and pmap[i-3] == 4: return i-3