def generate_key(): # Find prime number P using Miller-Rabin Method p = random.randint(10000, 100000) while not utils.isPrime(p): p = random.randint(10000, 100000) # Find prime divisor q = 0 for num in reversed(range(int(math.sqrt(p - 1)))): if ((p - 1) % num) == 0: if utils.isPrime(num): q = num break # Find primitive root g = 1 while g == 1: h = random.randint(2, p) g = utils.modular_power(h, (p - 1) / q, p) # Secret Key private_key = random.randint(1, p - 1) # Public Key Parameters y1 = utils.modular_power(g, private_key, p) y2 = utils.modular_power(y1, private_key, p) public_key = (g, y1, y2) return private_key, public_key, p
def validate(self): if isPrime(self.P): raise Exception("p not prime") if isPrime(self.Q): raise Exception("q not prime") if gcd(self.e, self.f) != 1: raise Exception("gcd(e, f) != 1")
def isTrunc( n ): f = n while f: if not isPrime( f ): return False f //= 10 m = int( log10( n ) + 1 ) while m: if not isPrime( n % ( 10 ** m ) ): return False m -= 1 return True
def randPrime(primeLength): assert primeLength > 1, 'Length of number much greather than 1' start, end = 10**(primeLength - 1), 10**primeLength start += int((end - start) * random.random()) start += start % 6 primes = [] for i in range(start, end, 6): if isPrime(i - 1): primes.append(i - 1) if isPrime(i + 1): primes.append(i - 1) if len(primes) > 100: break prime = random.choice(primes) return prime
def prob27(): # Considering quadratics of the form: # p(n) = n² + an + b, where |a| < 1000 and |b| < 1000 # 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. #b has to be prime, since our equation must hold for n=0 limit = 1000 maxN = maxA = maxB = 0 primes = utils.genPrimes(limit) for a in range(-limit + 1, limit + 1, 2): #a must be odd for b in primes: n = 1 #we know p(n) for n=0 is prime, so our function already generates at least 1 #prime while n**2 + a * n + b > 0 and utils.isPrime(n**2 + a * n + b): n += 1 if n > maxN: maxN = n maxA = a maxB = b return maxA * maxB
def odd_composites(): # numbers that are not prime and not 1 count: int = 1 while True: count += 2 # is odd if not isPrime(count): yield count
def prob41(): #pandigital primes limit = 7654321 #we exploit the property that if the sum of digits of a number is divisible by 3, the number is divisible by 3 numbers = "".join([str(i) for i in range(1,len(str(limit))+1)]) for x in range(limit,1,-2): if all(str(x).count(y) == 1 for y in numbers): if utils.isPrime(x): return x
def isCircular( n ): digits = int( log10( n ) ) for _ in xrange( digits + 1 ): if not isPrime( n ): return False # rotate the number n = rotated( n, digits ) return True
def testNdFactor(): for M in (1, 2, 3, 4, 5, 10, 15, 36, 37, 49, 97, 121, 0, -5): val = ndFactor(str(M)) utils.tprint(M, ':', val) if M < 2 or utils.isPrime(M): assert val == 'no' else: assert M % int(val) == 0
def testFactorUnary(): for M in (1,2,3,4,5,10,15,36,37,49,97,121): unaryM = '1'*M val = factorUnary(unaryM) utils.tprint(M, ':', val) if utils.isPrime(M): assert val == 'no' else: assert M % int(val) == 0
def prob7(): target = 10001 primeCount = 0 i = 0 while primeCount < target: if utils.isPrime(i): primeCount += 1 i += 1 return i-1
def nthPrime(n): num, count = 3, 1 while True: if isPrime(num): count += 1 if count == n: return num num += 2
def prob7(): target = 10001 primeCount = 0 i = 0 while primeCount < target: if utils.isPrime(i): primeCount += 1 i += 1 return i - 1
def prob41(): #pandigital primes limit = 7654321 #we exploit the property that if the sum of digits of a number is divisible by #3, the number is divisible by 3 numbers = "".join([str(i) for i in range(1,len(str(limit)) + 1)]) for x in range(limit,1,-2): if all(str(x).count(y) == 1 for y in numbers): if utils.isPrime(x): return x
def only_prime_rotations(n): ds = utils.digits(n, 10)[::-1] for _ in range(len(ds)): ds.append(ds.pop(0)) i = int(''.join(map(str, ds))) if not utils.isPrime(i): # print(i,"not prime",ds) return False # print(ds) return True
def Go(): nums = list() for k in xrange(9, 5, -1): for l in permutations(range(1, k)): i = getN(l) if i % 5 == 0 or i % 3 == 0 or i % 7 == 0: continue if isPandigital(i) and isPrime(i): nums.append(i) print(max(nums))
def getVal(limit): count = 1 candidate = 1 while (count < limit): candidate += 2 if (isPrime(candidate)): count += 1 return candidate
def main(): primes = [2, 3] i = primes[-1] while primes[-1] < 2000000: i += 2 # sieving would be faster, but I already wrote isPrime if isPrime(i): # print(i) primes.append(i) primes.pop() print(sum(primes))
def arithmetic_sequences(listofnumbers): listofprimes = [number for number in listofnumbers if isPrime(number)] prime_permutations = set() for i in listofprimes: for j in listofprimes: if (i - j) + i in listofprimes and 2 * i - j < i < j: if "0" not in list(str(j)): prime_permutations.add(((i - j) + i, i, j)) return prime_permutations
def isTrucatablePrimes(number: int) -> bool: # print(number) listofdigits: List[int] = numberToList(number) # print(listofdigits) lenList: int = len(listofdigits) # truncatable from left for i in range(lenList): # print(listofdigits[i:lenList]) if not isPrime(listToNumber(listofdigits[i:lenList])): # print(listofdigits[i:lenList]) return False # truncatable from right for i in range(lenList): # print(listofdigits[0:(i+1)]) if not isPrime(listToNumber(listofdigits[0 : (i + 1)])): # print(listofdigits[0:(i+1)]) return False return True
def main(): tests = [9, 15, 21, 25, 27, 33] assert all([test(i) for i in tests]) # for i in [9,15,21,25,27,33]: # print(i,test(i)) n = 3 # skip over primes while test(n) or isPrime(n): n += 2 if n % 1000000 == 0: print("at", n) print(n)
def maxPrimeFactor(number): ''' maxPrimeFactor takes a number and returns the largest prime factor for that number ''' # The largest factor of a number cannot be larger then the square root of the number maxFactor = int(number ** 0.5) while maxFactor > 1: if number % maxFactor == 0: if isPrime(maxFactor): return maxFactor maxFactor -= 1 # If the while loop did not return a value then the orginal number has to be prime return number
def test(n): """return true if number fits the conjecture""" # sum of a prime and twice a square # increase the square until n minus twice the square is never prime # n = p + 2*a**2, where p is prime # p = n - 2*a**2 # a = ((n-p)/2)**(1/2) for a in range(int((n / 2)**(1 / 2)), 0, -1): # print(n-2*i**2) # print(n,n-2*a**2,a) p = n - 2 * a**2 if isPrime(p): return True return False
def prob46(): #goldbach's other conjecture: from math import sqrt limit=6000 primes = utils.genPrimes(limit) compositeOdds = [i for i in range(9,limit,2) if not utils.isPrime(i)] for i in compositeOdds: canBeWritten = False for n in primes: if (i-n) % 2 == 0: #we need to check if (i-n)/2 is a perfect square. if it is, i can be written as described num = (i-n)/2 if num < 0: #this means we found no suitable prime break if not (math.sqrt(num)-int(math.sqrt(num))): canBeWritten=True break if not canBeWritten: return i
def prob46(): #goldbach's other conjecture: from math import sqrt limit = 6000 primes = utils.genPrimes(limit) compositeOdds = [i for i in range(9,limit,2) if not utils.isPrime(i)] for i in compositeOdds: canBeWritten = False for n in primes: if (i - n) % 2 == 0: #we need to check if (i-n)/2 is a perfect square. if it is, i #can be written as described num = (i - n) / 2 if num < 0: #this means we found no suitable prime break if not (math.sqrt(num) - int(math.sqrt(num))): canBeWritten = True break if not canBeWritten: return i
def prob27(): # Considering quadratics of the form: # p(n) = n² + an + b, where |a| < 1000 and |b| < 1000 # 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. #b has to be prime, since our equation must hold for n=0 limit = 1000 maxN = maxA = maxB = 0 primes = utils.genPrimes(limit) for a in range(-limit+1,limit+1,2): #a must be odd for b in primes: n = 1 #we know p(n) for n=0 is prime, so our function already generates at least 1 prime while n**2+a*n+b > 0 and utils.isPrime(n**2+a*n+b): n += 1 if n > maxN: maxN = n maxA = a maxB = b return maxA*maxB
from utils import isPrime def layerGen(): x = 2 s = 2 while True: yield xrange( x, x + s * 4 + 1 ) x = x + s * 4 s += 4 layer = 0 lgen = layerGen() primes, all = 0., 1 while primes / all > .1: for val in next( lgen ): if isPrime( val ): primes += 1 all += 1 layer += 1 # RELOOK
def primeLen( a, b ): n = 0 while isPrime( n ** 2 + a * n + b ): n += 1 return n
def iscomposite(n): return not isPrime(n)
from utils import primeGen, isPrime, isSquare, isEven def Goldbach( c ): for p in primeGen( c ): if isEven( c - p ) and isSquare( ( c - p ) / 2 ): return True c = 4 while isEven( c ) or isPrime( c ) or Goldbach( c ): c += 1 print c
from utils import isPrime, lexiPermGen print max( p for n in xrange( 10 ) for p in lexiPermGen( vals=xrange( 1, n ) ) if isPrime( p ) )
def sumOfPrimes(n): num = 3 while num < n: if isPrime(num): yield num num += 2
d5d6d7=357 is divisible by 7 d6d7d8=572 is divisible by 11 d7d8d9=728 is divisible by 13 d8d9d10=289 is divisible by 17 Find the sum of all 0 to 9 pandigital numbers with this property. """ from itertools import combinations from itertools import permutations from functools import reduce from math import sqrt from utils import isPrime from typing import List, Tuple assert isPrime(3) == True assert isPrime(10) == False listofdigits: str = "1234567890" numberofdigits: int = 10 digits: List[str] = list("1234567890") substringdigits: List[int] = [ int(digits[i] + digits[i + 1] + digits[i + 2]) for i, digit in enumerate(digits) if i > 0 and i <= 7 ] print("substrings of 0123456789:", substringdigits) listofPrimes: List[int] = [2, 3, 5, 7, 11, 13, 17]
def numberofPrimesQuadratic(a: int, b: int) -> int: n: int = 0 while isPrime(n ** 2 + n * a + b): n += 1 return n
def nextprime() -> Iterator[int]: number: int = 2 while True: if isPrime(number): yield number number += 1
""" Project Euler - Problem 7 SOLVED """ import utils if __name__ == "__main__": prime_count = 0 prime_threshold = 10001 i = 2 while True: if utils.isPrime(i): prime_count += 1 if prime_count == prime_threshold: print i break i += 1
"""Truncatable primes Problem 37 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. """ from math import sqrt from itertools import permutations from typing import List from utils import isPrime, nextprime assert isPrime(1) == False assert isPrime(0) == False assert isPrime(7) def listToNumber(numList: List[int]) -> int: s = "".join([str(i) for i in numList]) return int(s) assert listToNumber([1, 2, 3, 4]) == 1234 def numberToList(number: int) -> List[int]: return [int(digit) for digit in str(number)]
"""Consecutive prime sum Problem 50 The prime 41, can be written as the sum of six consecutive primes: 41 = 2 + 3 + 5 + 7 + 11 + 13 This is the longest sum of consecutive primes that adds to a prime below one-hundred. The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953. Which prime, below one-million, can be written as the sum of the most consecutive primes? """ from typing import List from utils import isPrime, nextprime primes = nextprime() primes_below12000 = [next(primes) for _ in range(1000)] maxlength = 0 maxprime = -1 for prime_min in range(len(primes_below12000)): for prime_max in range(prime_min, len(primes_below12000)): testsum = sum(primes_below12000[prime_min:prime_max]) if isPrime(testsum) and testsum < 1000000: if prime_max - prime_min > maxlength: maxlength = prime_max - prime_min maxprime = testsum print(f"The prime, {maxprime} is the sum of {maxlength} consectutive primes.")
def isCircularPrime(number: int) -> bool: for i in digit_rotations(number): if not isPrime(i): return False return True