Пример #1
0
def encrypt():
    # generating a prime numbers list
    prime_list = primes(1000)

    # choosing two random prime numbers from the list
    p = prime_list[random.randint(0, len(prime_list) - 1)]
    q = prime_list[random.randint(0, len(prime_list) - 1)]

    # n will be the modulus for the public and private keys
    n = p * q

    # calculating the totient
    m = (p - 1) * (q - 1)

    # choosing an integer e which is between 1 and the totient.
    # e must also be coprime to the totient, so choosing only prime
    # numbers inside that range would guarantee that e is coprime.
    e_list = primes(1000)
    e = e_list[random.randint(0, len(e_list) - 1)]

    # choosing a number d such that e*d has a remainder 1 when it is
    # divided by m.
    for d in range(2, 1000000):
        if (e * d) % m == 1:
            break

    # here, you take the user input and convert each character into
    # its appropriate ASCII number
    message = input("\nEnter message to encrypt: ")

    # the following list will contain all the ASCII numbers of the message
    ascii_list = [ord(char) for char in message]

    # the following list will contain all the encrypted values of each ASCII number
    enc_list = [(a**e) % n for a in ascii_list]

    alphabet = "abcdefghijklmnopqrstuvwxyz"
    encrypted_string = ""
    for encryption in enc_list:
        a = random.randint(
            13221, 561651616
        )  # just generating random numbers between key mashed numbers
        # concatenating a sequence of numbers and a letter into the final encrypted string
        encrypted_string += str(
            encryption * a) + "<>" + str(a) + alphabet[encryption % 26] + "<>"
    fname = str(e) + " " + str(n) + ".txt"
    print(encrypted_string, file=open(fname, 'w'))
    print(
        "\nYour message has been encrypted in a text file with format 'e n.txt'"
        .format(fname))
    print("Please keep note of the public keys: e = {0} end n = {1}".format(
        e, n))
    # check for '__this_folder_is_totally_not_suspicious__' folder
    # this folder will contain the private keys ... but .. shhh... you didn't need to know that
    if not os.path.isdir("__this_folder_is_totally_not_suspicious__"):
        os.mkdir("__this_folder_is_totally_not_suspicious__")
    store_priv = open("__this_folder_is_totally_not_suspicious__/" + fname,
                      "w")
    print("{0} {1}".format(d, n), file=store_priv)
Пример #2
0
def encrypt():
    # generating a prime numbers list
    prime_list = primes(1000)

    # choosing two random prime numbers from the list
    p = prime_list[random.randint(0, len(prime_list)-1)]
    q = prime_list[random.randint(0, len(prime_list)-1)]

    # n will be the modulus for the public and private keys
    n = p*q

    # calculating the totient
    m = (p - 1)*(q - 1)

    # choosing an integer e which is between 1 and the totient.
    # e must also be coprime to the totient, so choosing only prime
    # numbers inside that range would guarantee that e is coprime.
    e_list = primes(1000)
    e = e_list[random.randint(0, len(e_list)-1)]

    # choosing a number d such that e*d has a remainder 1 when it is
    # divided by m.
    for d in range(2, 1000000):
        if (e*d)%m == 1:
            break

    # here, you take the user input and convert each character into
    # its appropriate ASCII number
    message = input("\nEnter message to encrypt: ")

    # the following list will contain all the ASCII numbers of the message
    ascii_list = [ord(char) for char in message]

    # the following list will contain all the encrypted values of each ASCII number
    enc_list = [(a**e)%n for a in ascii_list]

    alphabet = "abcdefghijklmnopqrstuvwxyz"
    encrypted_string = ""
    for encryption in enc_list:
        a = random.randint(13221, 561651616) # just generating random numbers between key mashed numbers
        # concatenating a sequence of numbers and a letter into the final encrypted string
        encrypted_string += str(encryption * a) + "<>" + str(a) + alphabet[encryption%26] + "<>"
    fname = str(e) + " " + str(n) + ".txt"
    print(encrypted_string, file=open(fname, 'w'))
    print("\nYour message has been encrypted in a text file with format 'e n.txt'".format(fname))
    print("Please keep note of the public keys: e = {0} end n = {1}".format(e, n))
    # check for '__this_folder_is_totally_not_suspicious__' folder
    # this folder will contain the private keys ... but .. shhh... you didn't need to know that
    if not os.path.isdir("__this_folder_is_totally_not_suspicious__"):
        os.mkdir("__this_folder_is_totally_not_suspicious__")
    store_priv = open("__this_folder_is_totally_not_suspicious__/" + fname, "w")
    print("{0} {1}".format(d, n), file=store_priv)
Пример #3
0
def ticket838():
	dico = c.get('/bin/hackademy/exam/factoring/trial-division/A')
	n = dico['n']
	result = []
	for p in primes():		
		if isPrime(n):
			result.append(n)
			break
		if p > math.sqrt(dico['n']):
			break
		while (n % p == 0):
			result.append(p)
			n = n//p
	print(c.post('/bin/hackademy/exam/factoring',id=dico['id'],factors=result))
Пример #4
0
def prime_factors(n):
    '''Get the prime factors of n.'''
    if n < 2:
        return []
    factors = []
    xprimes = primes(n ** 0.5)
    while n > 1:
        try:
            prime = xprimes.pop(0)
            while prime:
                if n % prime == 0:
                    xprimes.insert(0, prime)
                    factors.append(prime)
                    n /= prime
                    break
                prime = xprimes.pop(0)
        except:
            return factors + [n]
    return factors
Пример #5
0
from primes import *


def is_truncatable(p):
    p = str(p)
    for i in range(1, len(p)):
        if not (is_prime(int(p[:-i])) and is_prime(int(p[i:]))):
            return False
    return True

print is_truncatable(97)

count = 0
found = []
for p in primes():
    if p > 10:
        if is_truncatable(p):
            count += 1
            found.append(p)
            print p
    if count == 11:
        break

print sum(found)
Пример #6
0
Файл: p41.py Проект: shuw/euler
from math import *
from primes import *
import copy

pSet = set(primes(10000000))

# 9 & 8 can be excluded from search space because
# the sum of digits to 9 and to 8 are multiples of 9 which means the base 10 number
# they form are also divisible by 9
digits = [7,6,5,4,3,2,1]

def findPandigitalPrimes(available, path):
    if len(available) == 0:
        n = 0
        for d in path: n = d + n * 10

        if n in pSet:
            return n
        return None            
    
    for d in available:
        a2 = copy.copy(available)
        a2.remove(d)
        
        path.append(d)
        n = findPandigitalPrimes(a2, path)
        if n != None: return n
        path.pop()

print 'Answer: ' + str(findPandigitalPrimes(digits,[]))
Пример #7
0
def time_primes(n=10):
    return primes(n)
Пример #8
0
# solution from the website
# Euler 60
from time import time
start = time()
from 60 import primes # Finds all prime numbers less than n
lst=primes(10000)

def isprime(n):
    for d in lst:
        if n%d==0 and d*d<=n:
            return False
        if d*d>n:
            return True
    
def p(x,y):
    if isprime(int(str(x)+str(y))) and isprime(int(str(y)+str(x))):
        return True
    else:
        return False

ans=(sum((a,b,c,d,e))
     for a in lst
     for b in lst
         if a<b and p(a,b)
     for c in lst
         if b<c and p(a,c) and p(b,c)
     for d in lst
         if c<d and p(a,d) and p(b,d) and p(c,d)
     for e in lst
         if d<e and p(a,e) and p(b,e) and p(c,e) and p(d,e))
Пример #9
0
	return True



def euclideTendu(a,b):
	r=a
	u=1
	v=0
	r2=b
	u2=0
	v2=1
	while (r2 != 0):
		q = r//r2
		rs = r
		us = u 
		vs = v
		r = r2
		u = u2
		v = v2
		r2 = rs - (q*r2)
		u2 = us - (q*u2)
		v2 = vs - (q*v2)
	return [r,u,v]


tab = []
for p in primes():
	tab.append(p)
	if len(tab) > 999:
		break
Пример #10
0
import bisect

from memoizer import Logger
from primes import *

def inc():
    n = 0
    yield 0
    while 1:
        n += 1
        if n == 1000:
            break
        yield n
        yield -n

primelist = primes(16000)
def consecutive_primes(a, b):
    n = 0
    y = n ** 2 + a * n + b
    #print "a", a, "b", b, "y", y
    while is_prime(y, primelist):
        n += 1
        y = n ** 2 + a * n + b
    #print "-------------------"
    #print "a", a, "b", b, "N", n
    return n

def foo(a):
    ns = map(lambda b: consecutive_primes(a, b), primelist)
    n = max(ns)
    print "a", a, n, "prime", primelist[ns.index(n)]
Пример #11
0
Файл: p46.py Проект: shuw/euler
from primes import *


pList = primes(10000)
pSet = set(pList)

def test(n):
    for p in pList:
        if p > n: break;
        if ((n-p) / 2) ** 0.5 % 1 == 0: return True
    return False

n = 1
while True:
    n += 2
    if n in pSet: continue
    if test(n) is False: break

print 'Answer: ' + str(n)
Пример #12
0
Файл: p49.py Проект: shuw/euler
from primes import *
from digits import *

pList = primes(10000) # need up to 4 digits
pSet = set(pList)

for i in range(len(pList)):
    p = pList[i]    
    if p < 1000: continue

    for j in range(i+1, len(pList)):
        p2 = pList[j]
        p3 = (p2 - p) + p2
        if (p2 - p) + p2 in pSet:
            if set(toList(p)) == set(toList(p2)) == set(toList(p3)):
                print (p, p2, p3)     
Пример #13
0
Файл: p58.py Проект: shuw/euler
from primes import *

primesUpTo = 2000000  # 2M
pList = primes(primesUpTo)
pSet = set(pList)


def isPrime(n):
    if n < primesUpTo:
        return n in pSet
    if n > primesUpTo ** 2:
        raise Exception("increase prime cache")

    # check if there are any prime divisors up to sqrt(n)
    checkUpTo = int(n ** 0.5) + 1
    for x in pList:
        if x > checkUpTo:
            return True
        if n % x == 0:
            return False


# Takes ~ minute to run
sides = 4
n = 1
d = 2  # delta
count = 0
total = 1
while True:
    total += sides
    for i in range(sides):