def confirmList(x): x = x[:] if (x == []): return False if (len(x) == 1): return pi.isPrime(x[0]) b = x[-1] for a in x[:-1]: p1 = (a * 10**(int(math.log(b, 10)) + 1) + b) p2 = (b * 10**(int(math.log(a, 10)) + 1) + a) if (not pi.isPrime(p1) or not pi.isPrime(p2)): return False return True
def confirmList(x): x = x[:] if(x == []): return False if(len(x) == 1): return pi.isPrime(x[0]) b = x[-1] for a in x[:-1]: p1 = (a * 10 ** (int(math.log(b,10))+1) + b) p2 = (b * 10 ** (int(math.log(a,10))+1) + a) if(not pi.isPrime(p1) or not pi.isPrime(p2)): return False return True
def decompose(num): num = str(num) result = [] for i in range(1, len(num)): if num[i] == "0": continue (x, y) = (int(num[:i]), int(num[i:])) if x > y: continue if isPrime(x) and isPrime(y) and isPrime(int(str(y) + str(x))): result.append((x, y)) return result
def confirmList(x, sieve): x = [str(a) for a in x] y = x[-1] c = max(list(sieve)) for z in x[:-1]: a = int(z + y) b = int(y + z) if (a not in sieve and a < c) or not pi.isPrime(a): return False if (b not in sieve and b < c) or not pi.isPrime(b): return False return True
def isPair(a, b, sieve): p1 = (a * 10**(int(math.log(b, 10)) + 1) + b) p2 = (b * 10**(int(math.log(a, 10)) + 1) + a) c = max(list(sieve)) if (p1 > c): if (not pi.isPrime(p1)): return False else: if (p1 not in sieve): return False if (p2 > c): if (not pi.isPrime(p2)): return False else: if (p2 not in sieve): return False return True
def solveBruteForce(top): # Define the upper limit upperLimit = 1 for i in xrange(1, top+1): upperLimit *= i #print upperLimit # Define the lower limit lowerLimit = 1 for i in xrange(1, top+1): if (prime.isPrime(i) == True): lowerLimit *= i #print lowerLimit # Check between the limits for num in xrange(lowerLimit, upperLimit+1): flag = True for j in xrange(1, top+1): if (num % j != 0): flag = False if (flag == True): return num # Worst case scenario return upperLimit
def isCircularPrime(x): size = math.floor(math.log(x,10))+1 for turn in range(size): if(not prime.isPrime(x)): return False x = rotateDigits(x) return True
def getPrimeFactors(num): factors = [] for i in reversed(xrange(num)): if (i != 0 and num % i == 0): if (prime.isPrime(i) == True): factors.append(i) return factors
def generateLine1(line1): if isPrime(line1[0] * 100 + line1[1] * 10 + line1[2]): def generateLine2(line1, line2): if isPrime(line2[0] * 100 + line2[1] * 10 + line2[2]): def generateLine3(line1, line2, line3): if not isPrime(line3[0] * 100 + line3[1] * 10 + line3[2]): return if not isPrime(line1[0] * 100 + line2[0] * 10 + line3[0]): return if not isPrime(line1[1] * 100 + line2[1] * 10 + line3[1]): return if not isPrime(line1[2] * 100 + line2[2] * 10 + line3[2]): return if not isPrime(line1[0] * 100 + line2[1] * 10 + line3[2]): return if not isPrime(line1[2] * 100 + line2[1] * 10 + line3[0]): return # print("{}\n{}\n{}\n".format(line1, line2, line3)) global cnt cnt += 1 hpapply(l, 3, lambda line3: generateLine3(line1, line2, line3)) hpapply(l, 3, lambda line2: generateLine2(line1, line2))
def largestPrimeFactor(num): global solution top = int(math.ceil(math.sqrt(num))) for i in range(2, top+1): if (num % i == 0): if (prime.isPrime(i) == True): solution = i
def isCircularPrime(x): size = math.floor(math.log(x, 10)) + 1 for turn in range(size): if (not prime.isPrime(x)): return False x = rotateDigits(x) return True
def visualize_isPrime(i, j): RANGE = range(i, j) data = [] crange = [] datap = [] prange = [] print("isPrime") for i in range(0, len(RANGE)): if prime.isPrime(RANGE[i]): datap.append(time_func(50, prime.isPrime, RANGE[i])) prange.append(RANGE[i]) else: data.append(time_func(50, prime.isPrime, RANGE[i])) crange.append(RANGE[i]) _, ax = plot.subplots() ax.set_title('Trial Division Run Time') ax.set_ylabel('Run Time (us)') ax.set_xlabel('Number n') plot.plot(crange, data, '.', color="b", alpha=0.5, label="Trial Division is Composite") plot.plot(prange, datap, '.', color="r", alpha=0.5, label="Trial Division is Prime") plot.legend() plot.show()
def factorize(n): factor = [] while True: m = prime.isPrime(n) if m == n: break n //= m return factor
def test_isprime(self): self.assertFalse(prime.isPrime(-1)) self.assertFalse(prime.isPrime(0)) self.assertFalse(prime.isPrime(1)) self.assertTrue(prime.isPrime(2)) self.assertTrue(prime.isPrime(17)) self.assertTrue(prime.isPrime(19)) self.assertFalse(prime.isPrime(21))
def primePermutations(): for i in range(0, len(fourDigitPrimes)): pi = fourDigitPrimes[i] pistr = sorted(str(pi)) for j in range(i+1, len(fourDigitPrimes)): pj = fourDigitPrimes[j] d = pj - pi pk = pj + d if isPrime(pk) and pistr == sorted(str(pj)) and pistr == sorted(str(pk)): yield '%d%d%d' % (pi,pj,pk)
def recursive(now, digit): if isPrime(now): if digit == 9: print(now) global cnt cnt += 1 else: for i in range(1, 10): new = now + i*(10**digit) recursive(new, digit + 1)
def main(): n = int(input('type any number : ')) result = prime.isPrime(n) if result: print(n, '은 소수야!') else: print(n, '은 ', result, '로 나눠져!') result = factorize(n) print(result)
def consecutiveSumPrimes(maxPrime): ps = list(takewhile(lambda x: x < maxPrime, primes())) for i in range(0, len(ps)): total = ps[i] for j in range(i+1, len(ps)): total += ps[j] if total > maxPrime: break if isPrime(total): count = j - i + 1 yield (total, count)
def test_isPrime(self): self.assertTrue(prime.isPrime(2)) self.assertTrue(prime.isPrime(3)) self.assertFalse(prime.isPrime(4)) self.assertFalse(prime.isPrime(49)) self.assertFalse(prime.isPrime(179426547)) self.assertTrue(prime.isPrime(179426549))
def allFactorSums(x): if (x not in dict1): if (pi.isPrime(x)): return [(x, 1)] else: total1 = [] facts = pi.getFactors(x)[1:] for i in facts: for j in allFactorSums(x // i): total1.append((i + j[0], 1 + j[1])) total1.append((i + x // i, 2)) dict1[x] = frozenset(total1) return dict1[x]
def allFactorSums(x): if(x not in dict1): if(pi.isPrime(x)): return [(x,1)] else: total1 = [] facts = pi.getFactors(x)[1:] for i in facts: for j in allFactorSums(x//i): total1.append((i+j[0],1+j[1])) total1.append((i+x//i,2)) dict1[x] = frozenset(total1) return dict1[x]
def isPrime(x): if(x < maxP+1): return x in sieveSet elif(x > l ** 8): return pi.isPrime(x) else: index = 0 p = sieve[0] while p**2 <= x: if(x % p == 0): return False index += 1 p = sieve[index] return True
def merge(x, y): mergedSet = list(y) if x[0] in y and x[1] in y: return None for i in x: if i in y: continue add = True for j in y: if not isPrime(int(str(i) + str(j))) or not isPrime(int(str(j) + str(i))): add = False break if add: mergedSet.append(i) if len(mergedSet) > len(y): mergedSet.sort() mergedSet = tuple(mergedSet) if not hash.has_key(mergedSet): hash[mergedSet] = 1 return mergedSet return None
def numSumsDigitsMax(value, numTerms, maxTerm): # single term if numTerms == 1: return 1 if prime.isPrime(value) and value <= maxTerm else 0 # all 2's if value == numTerms*2: return 1 # split into first term + remaining terms # max term in recursive call cannot be greater than first term maxFirstTerm = min(maxTerm, value - 2 * (numTerms - 1)) primes = prime.primes(maxFirstTerm + 1) return sum(numSumsDigitsMax(value - firstTerm, numTerms - 1, firstTerm) for firstTerm in primes)
def perm(): f = {} threshold = 10000 for x in range(2, threshold): yset = [i for i in primeTable if i < x / 2 + 1] for y in yset: z = x - y f[x, y] = sum([f[z, i] for i in yset if i < z / 2 + 1 and i >= y]) if isPrime(z): f[x, y] += 1 count = sum([f[x, i] for i in yset]) print x, count if count > 5000: return
def facgen(n): # base case: prime or 1, only 1 factorization if n == 1 or prime.isPrime(n): yield (n,) return # recursive case: peel off the first factor of n, # then combine with all factorizations of n/factor # Use memoization to avoid repeated factorization of previously seen numbers factor = firstFactor(n) for subfac in factorizations(n // factor): # combine by appending yield (factor,) + subfac # combine by multiplying each element of subfactor by the first factor for i in range(0, len(subfac)): yield replaceTupleElement(subfac, i, subfac[i] * factor)
def primeSet(): i = 11 result = [] while True: if isPrime(i): rc = decompose(i) if rc: for x in rc: for y in result: mergedSet = merge(x, y) if mergedSet: if len(mergedSet) >= 4: print mergedSet if len(mergedSet) == 5: return result.append(mergedSet) result.append(x) i += 1
def generateLine3(line1, line2, line3): if not isPrime(line3[0] * 100 + line3[1] * 10 + line3[2]): return if not isPrime(line1[0] * 100 + line2[0] * 10 + line3[0]): return if not isPrime(line1[1] * 100 + line2[1] * 10 + line3[1]): return if not isPrime(line1[2] * 100 + line2[2] * 10 + line3[2]): return if not isPrime(line1[0] * 100 + line2[1] * 10 + line3[2]): return if not isPrime(line1[2] * 100 + line2[1] * 10 + line3[0]): return # print("{}\n{}\n{}\n".format(line1, line2, line3)) global cnt cnt += 1
def visualize_isPrime(i, j): RANGE = range(i,j) data = [] crange = [] datap = [] prange = [] print("isPrime") for i in range(0, len(RANGE)): if prime.isPrime(RANGE[i]): datap.append(time_func(50,prime.isPrime,RANGE[i])) prange.append(RANGE[i]) else: data.append(time_func(50,prime.isPrime,RANGE[i])) crange.append(RANGE[i]) _,ax = plot.subplots() ax.set_title('Trial Division Run Time') ax.set_ylabel('Run Time (us)') ax.set_xlabel('Number n') plot.plot(crange,data,'.',color="b",alpha=0.5,label="Trial Division is Composite") plot.plot(prange,datap,'.',color="r",alpha=0.5,label="Trial Division is Prime") plot.legend() plot.show()
def p41(): """ Because of the properties of divisibility by 3, we only need to check up to 7 digits. Generate primes and pandigitals up to this range, and search """ prime = gen_primes() primes = [] p = 0 while (p <= int(math.sqrt(7654321))): p = next(prime) primes.append(p) digits = ['1', '2'] largest = 0 for i in range(3, 9): pandigits = makePandig(digits) for j in range(len(pandigits)): pandigits[j] = int(pandigits[j]) if (isPrime(pandigits[j], primes) == True): largest = pandigits[j] digits.append(str(i)) print(largest) return
# Answer: 7652413 # 1~2, 1~3, 1~5, 1~6, 1~8, 1~9 sum divisable by 3 # we test 1~4, 1~7 from prime import isPrime def f(n): if n == 1: return [1] l = f(n-1) r = [] d = 1 for i in range(n): for k in l: r.append(k/d * 10 * d + n*d + k%d) d *= 10 return r m = 0 for i in f(7): if i > m and isPrime(i): m = i if m == 0: for i in f(4): if i > m and isPrime(i): m = i print m
#17 16 15 14 13 30 #18 5 4 3 12 29 #19 6 1 2 11 28 #20 7 8 9 10 27 #21 22 23 24 25 26 spCorner = 1 #current number being visited along spiral cornerCount = 0 #how many corners have been traversed primeCount = 0 #how many primes ahve been traversed, for ratio step = 2 #addition step increases every four corners while((primeCount+1)/ float(cornerCount+1) > .1): for corner in range(4): spCorner += step if spCorner % 4000 <= 200: print(spCorner) print(primeCount/ float(cornerCount+1)) if prime.isPrime(spCorner): primeCount += 1 step += 2 cornerCount += 4 if primeCount / cornerCount < .1: print(str(cornerCount/2 + 1) + " at num="+str(spCorner)) print("Done") print(primeCount / cornerCount)
def primeDigitReplacements(p, d): for j in range(d, 10): x = replaceDigits(p, d, j) if isPrime(x): yield x
def test_is_prime(self): self.assertTrue(prime.isPrime(5)) self.assertFalse(prime.isPrime(10))
def test_isPrime_false(self): for n in self.not_prime_numbers: self.assertFalse(prime.isPrime(n))
#! include /usr/bin/python from prime import isPrime from itertools import * if __name__ == "__main__": b = 1000 found = False lis_type = [] while b < 10000: if isPrime(b): lis_type.append(sorted(str(b))) b += 1 for ele in lis_type: li = set() a = permutations(ele) for b in a: temp = 0 for c in b: temp = temp * 10 + int(c) if isPrime(temp) and len(str(temp)) == 4: li.add(temp) if len(li) < 3: continue c = permutations(li, 3) for d in c: d = sorted(d) if d[2] + d[0] == 2 * d[1] and d[0] != 1487: print d[0], d[1], d[2] found = True break
# Project Euler - Problem 37 # 2011-05-26 13:37:18 import time from prime import isPrime start = time.clock() count = 0 n = 22 sum = 0 while count < 11: if isPrime(n): flag = True l = r = str(n) bits = len(l) - 1 for i in range(0, bits): l = l[1: ] r = r[:-1] #print n, l, r if not isPrime(int(l)) or not isPrime(int(r)): flag = False break if flag: print n sum += n count += 1 n += 1 print sum
from prime import isPrime from sys import argv maxx = int(argv[1]) count = 0 i = 1 while i <= maxx: if isPrime(i): count = count + 1 i = i + 1 print 'Number of primes from 1 to', maxx, ':', count
def test_big_prime(self): self.assertTrue(prime.isPrime(prime.bigPrime()))
def main(): if settings.upload == True: sys.stdout.write("Searching for config.py file... ") config_file_test() info.title() # variable assignment num = int(input("Bottom value: ")) num1 = int(input("Top value: ")) diff = num1 - num list = [] i = 0 # csv row value in loop file_name = "prime" + str(num) + '-' + str(num1) + ".csv" # Runs function for x in range(num, num1): list.append([]) # create new nested list list[i].append(num) # append number in question to list percent = str(round(x / diff * 100, 1)) if (isPrime(num)): list[i].append("prime") # append 'prime' to list print(str(num) + ' prime'.rjust(20, '-'), end='') #alt could use sys.stdout.write() else: print(str(num) + ' null-'.rjust(20, '-'), end='') list[i].append("null") # append 'null' to list print(percent.rjust(20, '-') + '%') num = num + 1 i = i + 1 print(list) print('collected ' + str(len(list)) + ' prime numbers') sys.stdout.write("Initializing file write... ") # csv output with open("output/" + file_name, mode='w') as primes: writer = csv.writer(primes) writer.writerows(list) sys.stdout.write("Done\n") if settings.upload == True: sys.stdout.write("Initializing dropbox upload... \n") sys.stdout.write( "Go to https://www.dropbox.com to see more information\n") import config try: dat = data_transfer(config.oauth_result) dat.upload("output/" + file_name, "/output/" + file_name) sys.stdout.write("OAUTH CONNECTED SUCCESSFULLY\n") sys.stdout.write(file_name + " has been uploaded to dropbox\n") except dropbox.exceptions.BadInputError: print("WARNING: Don't have write permission") input("Change permission and click ENTER to fix") oauth_init(config.APP_KEY, config.APP_SECRET) importlib.reload(config) dat = data_transfer(config.oauth_result) sys.stdout.write("OAUTH CONNECTED SUCCESSFULLY\n") dat.upload("output/" + file_name, "/output/" + file_name) sys.stdout.write(file_name + " has been uploaded to dropbox\n") except ApiError as err: # This checks for the specific error where a user doesn't have # enough Dropbox space quota to upload this file if (err.error.is_path() and err.error.get_path().reason.is_insufficient_space()): sys.exit("ERROR: Cannot back up; insufficient space.") elif err.user_message_text: print(err.user_message_text) sys.exit() else: print(err) sys.exit() except: oauth_init(config.APP_KEY, config.APP_SECRET) importlib.reload(config) dat = data_transfer(config.oauth_result) dat.upload("output/" + file_name, "/output/" + file_name) sys.stdout.write(file_name + " has been uploaded to dropbox\n")
#importing prime function import prime n = int(input("enter dimention")) print("enter a nXn matrix") matrix = [] #to store NxN matrix primes = [] #to store prime numbers for i in range(0, n): exp = [] for i in range(0, n): e = int(input()) if prime.isPrime(e): primes.append(e) exp.append(e) matrix.append(exp) print("all prime numbers are : ") print(*primes) #unpacking of a list
import sys import prime # Get the number to test n = int(sys.argv[1]) # Get prime numbers up to the number primes = prime.generatePrimes(n) print(primes) print(len(primes)) print() # Determine whether the number is prime isPrime = prime.isPrime(n) print(n, " isPrime: ", isPrime) print() # Get the number's prime factors primeFactors = prime.getPrimeFactors(n) print("Prime factors:", primeFactors)
# written as the sum of a prime and twice a square. # # 9 = 7 + 2 x 1^2 # 15 = 7 + 2 x 2^2 # 21 = 3 + 2 x 3^2 # 25 = 7 + 2 x 3^2 # 27 = 19 + 2 x 2^2 # 33 = 31 + 2 x 1^2 # # It turns out that the conjecture was false. # # What is the smallest odd composite that cannot be written as the sum of a # prime and twice a square? # # Answer: 5777 from prime import isPrime n = 3 while True: i = n k = 2 while i > 0: if isPrime(i): break i -= k k += 4 if i <= 0: print n break n += 2
import os import prime x = 1024124214811 print prime.isPrime(x) def get_empty_spots(case): empty_spots = 0 for row in case: for spot in row: if spot == '?': empty_spots += 1 return empty_spots def fill_row(row): for i in xrange(1, len(row)): if row[i - 1] != '?' and row[i] == '?': row = row[0:i] + row[i - 1] + row[i + 1:] for i in xrange(len(row) - 2, -1, -1): if row[i + 1] != '?' and row[i] == '?': row = row[0:i] + row[i + 1] + row[i + 1:] return row def get_solutions(cases): for case in cases: for i in xrange(0, len(case)):
def test_small_21(): time.sleep(2) assert isPrime(21) == False
##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? from prime import isPrime i = 0 curr = 0 while i < 10002: curr += 1 if isPrime(curr): i += 1 print(curr)
def test_small_negative(): assert isPrime(-7) == False
def ccatPrimes(a,b): return prime.isPrime(int(str(a)+str(b))) and prime.isPrime(int(str(b)+str(a)))
def test_small_0(): assert isPrime(0) == False
def test_small_1(): assert isPrime(1) == False
##The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. ##Find the sum of all the primes below two million. from prime import isPrime print sum(x for x in range(1,2000000,2) if isPrime(x))
#! /usr/bin/env python3 from prime import isPrime from itertools import islice description = ''' Prime permutations Problem 49 The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual in two ways: (i) each of the three terms are prime, and, (ii) each of the 4-digit numbers are permutations of one another. There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, exhibiting this property, but there is one other 4-digit increasing sequence. What 12-digit number do you form by concatenating the three terms in this sequence? ''' fourDigitPrimes = [i for i in range(1001, 10000, 2) if isPrime(i)] def primePermutations(): for i in range(0, len(fourDigitPrimes)): pi = fourDigitPrimes[i] pistr = sorted(str(pi)) for j in range(i+1, len(fourDigitPrimes)): pj = fourDigitPrimes[j] d = pj - pi pk = pj + d if isPrime(pk) and pistr == sorted(str(pj)) and pistr == sorted(str(pk)): yield '%d%d%d' % (pi,pj,pk) print(list(islice(primePermutations(), 2)))
def test_isPrime_true(self): for n in self.prime_numbers: self.assertTrue(prime.isPrime(n))
def test_prime_choice(self): self.assertTrue(prime.isPrime(prime.primeChoice(5))) self.assertTrue(len(str(prime.primeChoice(5))) == 5)
def isPalindromeAndPrime(n): return palindrome(n) and isPrime(n)