def IsPrimeTruncatable(n, ndigits): if (n > 100): if (prime.isprime(n) == False): for i in range(2, ndigits): if (prime.isprime(n // 10**i) == False or prime.isprime(n % 10**i) == False): return False
def N(d,n=10): """For an n-digit prime, d is the digit that reappears.""" primes,dict = [], M() if dict[d] == n-1: to_permute = list(repeat(str(d),n)) #['1','1','1','1'] digits = [str(k) for k in range(10) if k!=d] current_permute = int("".join(to_permute)) if prime.isprime(current_permute): primes.append(current_permute) for i in range(n): for digit in digits: to_permute[i] = digit cur_num = int("".join(to_permute)) if prime.isprime(cur_num): primes.append(cur_num) to_permute[i] = str(d) return primes if dict[d] == n-2: to_permute = list(repeat(str(d),n)) #['1','1','1','1'] digits = [str(k) for k in range(10) if k!=d] double_digits = list(product(digits,digits)) current_permute = int("".join(to_permute)) if prime.isprime(current_permute): primes.append(current_permute) for i in range(n-1): for j in range(1,n): for pair in double_digits: to_permute[i] = pair[0] to_permute[j] = pair[1] cur_num = int("".join(to_permute)) # print "on",cur_num if prime.isprime(cur_num): # print cur_num,"PRIME" primes.append(cur_num) to_permute[i] = str(d) to_permute[j] = str(d) return [k for k in primes if len(str(k))==n]
def l_r_primes(n): prime_left = prime_right = False for i in xrange(1, len(str(n))): l = n % pow(10, i) r = n / pow(10, i) if (not prime.isprime(l)) or (not prime.isprime(r)): return False return True
def test_time_taken_to_calculate(): t0 = time.time() for i in range(2, 100000): prime.isprime(i) t1 = time.time() t = t1 - t0 assert t < 0.4
def answer(): # observation: cannot be 8 or 9 due to divisibility by 3 for n in range(7, 0, -1): possibilities = map(tuple_to_int, permutations(range(n, 0, -1))) for candidate in possibilities: if isprime(candidate): return candidate
def f(): for i in reversed(range(1, 547)): for j in range(1, 549-i): print j, i if isprime(sum(islice(sieve, j, i))): print j-i+1 return sum(islice(sieve, j, i))
def bruteforce(): count=1 # 1/2 is special for d in range(3,N+1): if prime.isprime(d): count+=d-1 else: count+=count_bruteforce(d) # error
def answer(limit=1000000): _refresh(limit // pow(10, sqrt(log10(limit))-1)) for length in range(int(sqrt(limit)), 0, -1): for end in range(len(prime_list), length-1, -1): candidate = sum(prime_list[end-length:end]) if candidate < limit and isprime(candidate): return candidate
def answer(limit=1000000): _refresh(limit // pow(10, sqrt(log10(limit)) - 1)) for length in range(int(sqrt(limit)), 0, -1): for end in range(len(prime_list), length - 1, -1): candidate = sum(prime_list[end - length:end]) if candidate < limit and isprime(candidate): return candidate
def check_length(n, below): maxprime = 0 for x in xrange(0, below): total = sum(prime.prime_list[x:x+n]) if total > below: break if prime.isprime(total): maxprime = total return maxprime
def gen_pnr(size, m): while True: # 1 шаг p = prime.gen_prime(size) assert p % 4 == 1 assert sympy.isprime(p) # 2 шаг (страница 168, алгоритм 7.8.1) a, b = get_zi_factors(p, 1) assert a * a + b * b == p # 3 шаг t_set = [2 * a, -2 * a, 2 * b, -2 * b] for t in t_set: n = p + 1 + t rs = [n // 2, n // 4] for r in rs: if prime.isprime(r): assert sympy.isprime(r) # шаг 4 if p != r: for i in range(1, m + 1): if pow(p, i, r) == 1: break else: return p, n, r
def ProjectEuler37(): """ 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. NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes. Solution: 1 is not prime, so two digits can only be 37 73 then, for number has 3 or more digits, those must be started and ended with 3 or 7 but the digits between can be combination_with_repeation of [1,3,7,9] """ count = 2 numbers = [ 37, 73, 23, 53 ] # I miss the first two 23, 35, filter the 2digits combination of [2 3 5 7] MaxDigits = 10 TotalNo = 11 for d in range(3, MaxDigits + 1): # generate a list of possible numbers for n in ListOfCandiates(d): if (all(prime.isprime(i) for i in ListOfTruncatble(n, d))): count = count + 1 numbers.append(n) print(n) if (len(numbers) == TotalNo): break if (len(numbers) == TotalNo): break print(numbers) print(sum(numbers))
def problem10(): """ The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. Answer: 142913828922 """ from prime import isprime print("problem10:", sum([i for i in range(2, 2000000) if isprime(i)]))
def is_left_truncatable(i): while True: if prime.isprime(i): if i > 10: i = int("".join(list(str(i))[1::])) else: return True else: return False
def countProperFaction(d): """ for non-prime number, get the list of factor proper factions for denumerator no bigger than 1000: 304191 (tested correctly) """ if prime.isprime(d): return (d-1) else: #return count_bruteforce(d) return factorset_union(d)
def problem58(): numOnDiagonal, width, noOfPrimes = 13, 7, 8 while noOfPrimes*10 > numOnDiagonal: nextWidth, square = width+2, width*width nextSquare = nextWidth*nextWidth result = xrange(square+width+1, nextSquare+1, width+1) noOfPrimes = noOfPrimes+ len(filter(lambda n: prime.isprime(n), result)) numOnDiagonal = numOnDiagonal+4 width = nextWidth return width
def answer(alim=1000, blim=1000): maxn = 0 for a in range(-alim+1, alim): for b in range(-blim+1, blim): n = 0 while isprime(pow(n, 2) + a*n + b): n += 1 if n > maxn: maxa, maxb, maxn = a, b, n return maxa * maxb
def main(): i = 11 t = 10 res = 0 while i > 0: if prime.isprime(t) and l_r_primes(t): res += t i -= 1 t += 1 print res
def answer(): for candidate in count(3, 2): if isprime(candidate): continue for p in prime_list: remainder = candidate - p root = sqrt(remainder // 2) if root == int(root): break else: return candidate
def answer(): for candidate in count(3, 2): if isprime(candidate): continue for p in prime_list: remainder = candidate - p root = sqrt(remainder//2) if root == int(root): break else: return candidate
def phi(n): """ if it is prime number, n/phi(n) is small near 1 but for prime number phi(n)=n-1, """ if isprime(n): return n - 1 else: s = [] #to-do return len(s)
def is_right_truncatable(i): while True: if prime.isprime(i): if i > 10: a = list(str(i)) a.pop() i = int("".join(a)) else: return True else: return False
def f(n): result = [] number = 0 for i in count(91): if i%2 == 0 or i%5 == 0: continue if (not isprime(i)) and is_ok(i): result.append(i) number += 1 if number == n: break return sum(result)
def pandigital(order): nums = [str(i) for i in xrange(1, order+1)] product = [] for num in per(nums): num = ''.join(num) if isprime(int(num)) and check(num, order): product.append(int(num)) else: continue if product: return max(product) else: return None
def prime_family_length(n, digits): if cache.has_key((n, digits)): return cache[n, digits] num, nums, count = list(str(n)), [], 0 if len(dict.fromkeys(num[d] for d in digits).keys()) > 1: return cache.setdefault((n, digits), 0) # The digits must have the same number for d in range(0 in digits and 1 or 0, 10): # Ensure 0 is not the first digit for x in digits: num[x] = str(d) n = int(''.join(num)) if prime.isprime(n): count += 1 nums.append(n) for n in nums: cache[n, digits] = count return count
def e58(): maxnum = 20000 prime_count = 0 count = 1 for n in xrange(2, maxnum): count += 4 x = (2 * n - 1) ** 2 for m in range(1, 4): if prime.isprime(x - 2 * (n - 1) * m): prime_count += 1 ratio = float(prime_count) / count if ratio <= 0.1: print 2 * n - 1, prime_count, '/', count, '=', ratio break
def answer(): for numbers in combinations_with_replacement(range(10), 4): perms_l = [digits_to_num(n) for n in permutations(numbers)] perms_s = set(perms_l) for fst_index, fst in enumerate(perms_l): if fst <= 1487: # rule out given value continue for snd_index in range(fst_index + 1, len(perms_l)): snd = perms_l[snd_index] dif = snd - fst if dif == 0: continue thrd = snd + dif if thrd in perms_s: if all(isprime(n) for n in (fst, snd, thrd)): return fst, snd, thrd
def answer(): for numbers in combinations_with_replacement(range(10), 4): perms_l = [digits_to_num(n) for n in permutations(numbers)] perms_s = set(perms_l) for fst_index, fst in enumerate(perms_l): if fst <= 1487: # rule out given value continue for snd_index in range(fst_index+1, len(perms_l)): snd = perms_l[snd_index] dif = snd-fst if dif == 0: continue thrd = snd+dif if thrd in perms_s: if all(isprime(n) for n in (fst, snd, thrd)): return fst, snd, thrd
#!/usr/bin/python3 import prime MAX = 10000 prime._refresh(MAX) squares = dict.fromkeys((x*x for x in range(1, MAX)), 1) for x in range(35, MAX, 2): if not prime.isprime(x): is_goldbach = 0 for p in prime.prime_list: if p >= x: break key = (x-p)/2 if key in squares: is_goldbach = 1 break if not is_goldbach: print(x) break
from math import sqrt import prime primes = filter(lambda k: prime.isprime(k), xrange(2,51)) mult = lambda x: reduce(lambda y, z: y * z, x, 1) translate = lambda x: mult(primes[i] ** ((x[i] - 1) // 2) for i in range(len(x))) def generator(limit): l = [1] * 14 while l[13] < limit: i = 13 while i > 0 and (l[i] == l[i-1]): l[i] = 1 i -= 1 l[i] += 2 yield l if __name__ == '__main__': result = min(translate(l) for l in generator(13) if mult(l) > 4000000) print("The result is:", result)
def listprimes(): for i in range(250): if (p.isprime(i)): print(i)
def test_seven_is_prime(self): self.assertTrue(prime.isprime(7))
def test_below2_notprime(self): for i in xrange(1, -10, -1): self.assertFalse(prime.isprime(i), msg = "Prime numbers must be greater than 1.")
def test_455_not_prime(self): self.assertFalse(prime.isprime(452))
from prime import is_prime_prob, isprime import time base = 2 exponent = 21701 starttime = time.time() count = 0 try: while True: cur = time.time() print(f"Checking {base}^{exponent}... ", end='') if not isprime(exponent): exponent += 2 print() continue if is_prime_prob(base**exponent - 1): print(f"M({exponent}) is probably prime") break exponent += 2 count += 1 end = time.time() - cur print(f"{end:.2f} seconds") except KeyboardInterrupt: print("Found {} probable primes in {} seconds".format( count, time.time() - starttime))
get_ipython().run_cell_magic('writefile', 'prime.py', "'''\nIt is a prime number\n'''\ndef isprime(num):\n '''\n It is\n '''\n if num in(0, 1):\n return False\n for prime in range(2, num-1):\n if num % prime == 0:\n return False\n return True") # In[4]: get_ipython().system(' pylint prime.py') # In[5]: import prime prime.isprime(199) # # USING UNIT TEST # In[6]: get_ipython().run_cell_magic('writefile', 'newprime.py', '\nimport unittest\nimport prime\n\nclass primenumber(unittest.TestCase):\n def testprime(self):\n Number = 32\n result = prime.isprime(Number)\n self.assertEquals(result, False)\n\n \n def testprimenum(self):\n Num = 199\n res = prime.isprime(Num)\n self.assertEquals(res, True)\n\n \n \nif __name__ == "__main__":\n unittest.main()') # In[7]: get_ipython().system(' python newprime.py')
def is_prime(n): return prime.isprime(n)
import root import prime import key li = [] print("give the range in which you want prime numbers") print("start=", end=" ") lower = int(input()) print("last=", end=" ") print("should no exceed 1024", end=" ") upper = int(input()) print("prime between", lower, "and", upper, "are:") for num in range(lower, upper): if (prime.isprime(num)): print(num, end=" ") li.append(num) print() print("select a prime", end=" ") q = int(input()) if q not in li: f1 = 1 while (f1): if q not in li: print("please select the prime number from below list only") print(li) q = int(input()) if q in li: f1 = 0 print("primitive roots list") li = [] print("enter lower and upper limits of primitive roots") print("upper limit should not execeed " + str(q))
def is_8_prime_family(p, d): c = 0 for r in '0123456789': np = int(string.replace(p, d, r)) if(np > 100000 and np < 999999 and prime.isprime(np)): c += 1 return c==8
#!/usr/bin/env python # -*- coding: utf-8 -*- import prime max_pair = (0, 0, 0) for a in xrange(-999, 1000): for b in xrange(max(2, 1 - a), 1000): # b >= 2, a + b + 1 >= 2 n, count = 0, 0 while True: v = n * n + a * n + b prime._refresh(v) if prime.isprime(v): count = count + 1 else: break n = n + 1 if count > max_pair[2]: max_pair = (a, b, count) print max_pair[0] * max_pair[1]
def is_truncatable_prime(n): n_str = str(n) if len(n_str) == 1: return False leftwise = [int(n_str[:i]) for i in range(1, len(n_str))] rightwise = [int(n_str[i:]) for i in range(len(n_str))] return all(isprime(i) for i in chain(leftwise, rightwise))
def test_prime_positive(): assert prime.isprime(2) == True assert prime.isprime(20) == False assert prime.isprime(3) assert not prime.isprime(4)
import prime print prime.prime(11) print prime._isprime(32) print prime.isprime(11)
def test_missing_param(): with pytest.raises(ValueError) as ex_info: prime.isprime(-2) assert ex_info.type == ValueError
def test_zeronot_prime(self): self.assertFalse(prime.isprime(0), msg = "Prime numbers must be greater than 1.")
def test_check_range_of_prime(): with pytest.raises(TypeError): prime.isprime(False)
def test_five_is_prime(self): self.assertTrue(prime.isprime(5))
def test_check_prime_test(): assert prime.isprime(200) == False
It turns out that the formula will produce 40 primes for the consecutive values n = 0 to 39. However, when n = 40, 402 + 40 + 41 = 40(40 + 1) + 41 is divisible by 41, and certainly when n = 41, 41^2 + 41 + 41 is clearly divisible by 41. Using computers, the incredible formula n^2 - 79n + 1601 was discovered, which produces 80 primes for the consecutive values n = 0 to 79. The product of the coefficients, -79 and 1601, is -126479. Considering quadratics of the form: n^2 + an + b, where |a| <= 1000 and |b| <= 1000 where |n| is the modulus/absolute value of n e.g. |11| = 11 and |4| = 4 Find the product of the coefficients, a and b, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n = 0. ''' import prime max_pair = (0,0,0) for a in xrange(-999, 1000): for b in xrange(max(2, 1-a), 1000): # b >= 2, a + b + 1 >= 2 n, count = 0, 0 while True: v = n*n + a*n + b prime._refresh(v) if prime.isprime(v): count = count + 1 else: break n = n + 1 if count > max_pair[2]: max_pair = (a,b,count) print max_pair[0] * max_pair[1]
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, absolute_import, division """ We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime. What is the largest n-digit pandigital prime that exists? """ digits = "123456789" from prime import isprime from itertools import permutations from tuple_list_to_int_list import tuple_list_to_int_list for i in range(9, 3, -1): l = [ j for j in tuple_list_to_int_list(permutations(digits[:i])) if isprime(j) ] #print i, l if any(l): print("largest n-digit pandigital prime ", max(l)) break