예제 #1
0
def prime(k):
    while True:
        q = Prime.prime(k)
        p = 2*q+1
        test = Prime.miller(p, 100)
        if test:
            return p
예제 #2
0
파일: RSA.py 프로젝트: YuqianHou/RSA
def get_RSAKey():
    RSAKey = {}

    start = time.perf_counter()
    prime_arr = Prime.get_rand_prime_arr(2)
    p = prime_arr[0]
    q = prime_arr[1]
    while p == q:
        q = random.choice(prime_arr)
    end = time.perf_counter()

    n = p * q
    s = (p - 1) * (q - 1)
    a = 65537
    b = Prime.mod_inverse(a, s)

    print("随机生成的素数p =", p)
    print("随机生成的素数q =", q)
    print('素数生成的时间为:', end - start, 's')

    print("n = pq =", n)
    print("利用Euclidean算法生成的私钥a =", a)
    print("利用扩展Euclidean算法生成的公钥b =", b)

    puk = [n, a]
    prk = [n, b]
    RSAKey['puk'] = puk
    RSAKey['prk'] = prk
    return RSAKey
예제 #3
0
def procgrid3d_to_2d(pex, pey, pez):

    p = Prime()
    p1 = p.factorize(pex)
    p2 = p.factorize(pey)
    p3 = p.factorize(pez)
    ptot = sorted(p1 + p2 + p3, reverse=True)

    nprow = 1
    npcol = 1
    for i in range(len(ptot) / 2):
        npcol *= ptot[2 * i]
        nprow *= ptot[2 * i + 1]

    if (len(ptot) - len(ptot) / 2 * 2 == 1):
        npcol *= ptot[len(ptot) - 1]

    return nprow, npcol
예제 #4
0
 def SetMod(self, mod):
     # Set self.mod
     # self.mod should be a prime
     if not isinstance(mod, int):
         raise Error.ModTypeError
     if (not Prime.IsPrime(mod)) and mod != 0:
         raise Error.ModValueError
     self.mod = mod
     self._Mod()
예제 #5
0
def count_perm(n, max_sub, res = {(0,0):1}):
   if (n,max_sub) in res:
      return res[(n,max_sub)]
   p = 0
   for i in Prime.primesLessThan(max_sub):
      c = count_perm(n - i,min(i,n-i))
      p += c
   res[(n,max_sub)] = p
   return p
예제 #6
0
파일: KeyRSA.py 프로젝트: immrhiep/RSA-ECC
def generateRsaKey(size=1024, e=65537):
    "Tạo khoá RSA theo PKCS#1 với kích thước mặc định là 1024-bits"
    d = 1
    while True:
        p = Prime.getPrime(size)
        q = Prime.getPrime(size)
        if RsaMath.gcd((p - 1), e) == 1 and RsaMath.gcd((q - 1), e) == 1:
            break

    n = p * q
    lam_da = ((p - 1) * (q - 1)) / RsaMath.gcd((p - 1), (q - 1))

    while d < 2**(size / 2):
        d = RsaMath.mod_inverse(e, lam_da)

    publicKey = (n, e)
    privateKey = (n, d)

    return privateKey, publicKey
예제 #7
0
파일: RSA.py 프로젝트: zhexuejia53/RSA
def get_RSAKey():
    RSAKey = {}
    prime_arr = Prime.get_rand_prime_arr(2)
    p = prime_arr[0]
    q = prime_arr[1]
    while p == q:
        q = random.choice(prime_arr)
    n = p * q
    s = (p - 1) * (q - 1)
    e = 65537
    d = Prime.mod_inverse(e, s)
    print "p = ", p, ",q = ", q
    print "n = ", n
    print "e = ", e, ",d = ", d
    puk = [n, e]
    prk = [n, d]
    RSAKey['puk'] = puk
    RSAKey['prk'] = prk
    return RSAKey
예제 #8
0
 def test_prime(self):
     self.assertEqual(Prime.is_prime(3), True)
     print(Prime.is_prime(3))
     self.assertEqual(Prime.is_prime(19), True)
     print(Prime.is_prime(19))
     self.assertEqual(Prime.is_prime(12), False)
     print(Prime.is_prime(12))
예제 #9
0
def prime_factor(num):
    import Prime
    prime_factor_list = []
    factor = 2
    while num != 1:
        if not Prime.prime(factor) :
            factor += 1
            continue
        if num % factor != 0:
            factor += 1
            continue
        else:
            num = num / factor
            prime_factor_list.append(factor)
    return prime_factor_list
예제 #10
0
class PrimeTest(unittest.TestCase):
	def setUp(self):
		self.prime = Prime()

	def test_number_less_than_zero_not_prime(self):
		self.assertFalse(self.prime.isPrime(-1))

	def test_1_is_not_prime(self):
		self.assertFalse(self.prime.isPrime(1))

	def test_2_is_prime(self):
		self.assertTrue(self.prime.isPrime(2))

	def test_4_is_not_prime(self):
		self.assertFalse(self.prime.isPrime(4))

	def test_5_is_prime(self):
		self.assertTrue(self.prime.isPrime(5))

	def test_massive_number_is_prime(self):
		self.assertTrue(self.prime.isPrime(1066340417491710595814572169))

	def test_massive_even_number_is_not_prime(self):
		self.assertFalse(self.prime.isPrime(1066340417491710595814572168))
예제 #11
0
class PrimeTest(unittest.TestCase):
    def setUp(self):
        self.prime = Prime()

    def test_number_less_than_zero_not_prime(self):
        self.assertFalse(self.prime.isPrime(-1))

    def test_1_is_not_prime(self):
        self.assertFalse(self.prime.isPrime(1))

    def test_2_is_prime(self):
        self.assertTrue(self.prime.isPrime(2))

    def test_4_is_not_prime(self):
        self.assertFalse(self.prime.isPrime(4))

    def test_5_is_prime(self):
        self.assertTrue(self.prime.isPrime(5))

    def test_massive_number_is_prime(self):
        self.assertTrue(self.prime.isPrime(1066340417491710595814572169))

    def test_massive_even_number_is_not_prime(self):
        self.assertFalse(self.prime.isPrime(1066340417491710595814572168))
예제 #12
0
import Prime
x = int(input("Enter number of elements: "))
Arr = list()
Sum = 0

for i in range(x):
    print("Enter number", (i + 1))
    no = int(input())
    if Prime.ChkPrime(no) is True:
        Sum = Sum + no
    Arr.append((no))
print(Arr)
print("Addition of Prime numbers in the List is ", Sum)
예제 #13
0
import Prime
from itertools import permutations

max_prime = 10000000
ps = set(Prime.prime_seive(max_prime))

done = False
for p in Prime.primes:
   pstr = str(p)
   for d in set(pstr):
      family = []
      for i in "0123456789":
         f = int(pstr.replace(d,i))
         if not len(str(f)) == len(pstr):
            continue
         if f in ps:
            family.append(f)
      if len(family) == 8:
         done = True
         print family
         break
   if done : break




예제 #14
0
import Prime


Prime.prime_seive(100000)
triangle = 1
i = 1
while Prime.factor(triangle).getNdivisors() < 500:
   i += 1
   triangle += i

print triangle

예제 #15
0
	def setUp(self):
		self.prime = Prime()
예제 #16
0
      for b in np.arange(1,10, dtype = float):
         if a == b : continue
         if (i*10+a)/(i*10+b) == a/b and (i*10+a)/(i*10+b) < 1:
            print (i*10+a),'/',(i*10+b)
            numerators.append(i*10+a)
            denominators.append(i*10+b)
         if (i+a*10)/(i*10+b) == a/b and (i+a*10)/(i*10+b) < 1:
            print (i+a*10),'/',(i*10+b)
            numerators.append(i+a*10)
            denominators.append(i*10+b)
         if (i+a*10)/(i+b*10) == a/b and (i+a*10)/(i+b*10) < 1:
            print (i+a*10),'/',(i+b*10)
            numerators.append(i+a*10)
            denominators.append(i+b*10)
         if (i*10+a)/(i+b*10) == a/b and (i*10+a)/(i+b*10) < 1:
            print (i*10+a),'/',(i+b*10)
            numerators.append(i*10+a)
            denominators.append(i+b*10)

top = int(np.prod(numerators))
bot = int(np.prod(denominators))

Prime.prime_seive(max(top,bot))

pt = Prime.primeFactors(top)
pb = Prime.primeFactors(bot)
gcd = pt.GCD(pb).getValue()

print top,bot,gcd
print top/gcd, bot/gcd
예제 #17
0
import Prime

from Tools import pandigitals

max_pan = 0
# Note: for n=8,9 all pandigitals are divisible by 9
primeset = set(Prime.prime_seive(int(1e7)))
for i in [7,6,5,4,3,2,1]:
   for p in pandigitals(i):
      if p in primeset:
         max_pan = max(p,max_pan)
   if max_pan:
      print max_pan
      break


예제 #18
0
import Prime

primeset = set(Prime.prime_seive(999999))

total = 0
for p in primeset:
   #left
   pstr = str(p)
   if len(pstr) == 1 : continue
   truncatable = True
   for i in range(1,len(pstr)):
      if not int(pstr[-i:]) in primeset : truncatable = False
      if not int(pstr[:i]) in primeset : truncatable = False
   if truncatable:
      print p
      total += p
print total
예제 #19
0
import Prime

n = 1000000
primeset = set(Prime.prime_seive(n))



total = 0
for max_n,p in enumerate(Prime.primes):
   total += p
   if total > n:
      break

l = max_n

lb = 5
while l > lb:
   for i in range(Prime.n_primes - l + 1):
      s = sum(Prime.primes[i:i+l]) 
      if s > n :
         break
      if sum(Prime.primes[i:i+l]) in primeset:
         print l,Prime.primes[i:i+l],sum(Prime.primes[i:i+l])
         l = lb
         break

   l -= 1


예제 #20
0
import Prime

def quad_prime(a,b,prime_set):
   n = 0
   x =  n**2 + a*n + b 
   while x in prime_set:
      x =  n**2 + a*n + b 
      yield x
      n+=1
      



Prime.prime_seive(100000)
prime_set = set(Prime.primes)

maximum = (0, 0, 0)
for b in Prime.primes:
   length = 0
   if b > 1000:
      break
   for a in xrange( 1-b, 1000 ):
      l = len([p for p in quad_prime(a,b,prime_set) ] )
      maximum = max(maximum,(l,a,b))



print maximum, maximum[1]*maximum[2]
예제 #21
0
import Prime as p

primeset = set(p.prime_seive(9999))


def is_permutation(one,two):
   return sorted(str(one)) == sorted(str(two))

for i in range(p.n_primes):
   if p.primes[i] < 1000 : continue
   for j in range(i+1,p.n_primes):
      if p.primes[j] < 1000 : continue
      if not is_permutation(p.primes[i], p.primes[j]):
         continue
      third = 2*p.primes[j] - p.primes[i]
      if third in primeset and is_permutation(p.primes[j],third):
         print p.primes[i], p.primes[j],third



예제 #22
0
import Prime

print [p for p in Prime.getNPrimes(10001)][-1]

예제 #23
0
파일: RSA.py 프로젝트: YuqianHou/RSA
def encryption(plaintext, puk):
    return Prime.quick_pow_mod(plaintext, puk[1], puk[0])
예제 #24
0
## EMIRP
##
## challenge #67 (easy)
## http://www.reddit.com/r/dailyprogrammer/comments/vfylp/6222012_challenge_68_easy/
##
##
## [email protected]
##

import Prime
num = int(raw_input("Enter a number: "))
emirp_list = []
for i in xrange(10, num + 1):
    if Prime.prime(i):
        temp = int(str(i)[::-1])
        if Prime.prime(temp) and i != temp:
            emirp_list.append(str(i))
print ", ".join(emirp_list)
예제 #25
0
def is_right(five):
    for p1, p2 in itertools.permutations(five, 2):
        if Prime.is_prime(str(p1) + str(p2)) == False:
            return False
    return True
예제 #26
0
import Prime
from collections import deque


primeset = set(Prime.prime_seive(1000000))

circulars = set()
for p in primeset:
   strp = deque(str(p))
   cycles = set()
   isCircular = True
   for i in range(len(strp)):
      strp.rotate(1)
      i = int(''.join(map(str, strp)))
      if i in primeset:
         cycles.add(i)
      else:
         isCircular = False
   if isCircular:
      circulars = circulars | cycles


print (circulars, len(circulars))






예제 #27
0
## EMIRP
##
## challenge #67 (easy)
## http://www.reddit.com/r/dailyprogrammer/comments/vfylp/6222012_challenge_68_easy/
##
##
## [email protected]
##

import Prime
num = int(raw_input("Enter a number: "))
emirp_list = []
for i in xrange(10,num+1):
    if Prime.prime(i):
        temp = int(str(i)[::-1])
        if Prime.prime(temp) and i != temp:
            emirp_list.append(str(i))
print ", ".join(emirp_list)
예제 #28
0
파일: RSA.py 프로젝트: YuqianHou/RSA
def decryption(ciphertext, prk):
    return Prime.quick_pow_mod(ciphertext, prk[1], prk[0])
예제 #29
0
 def __init__(self, p, a, k):
     self.p = p
     self.a = a
     self.k = k
     self.alpha = Prime.primitiveRoot(p)
     self.beta = power(self.alpha, a, p)
예제 #30
0
import Tools
import Prime

n = 10**7
Prime.prime_seive(n)
print  min( [ (n/float(t),n,t) for n,t in Prime.totient(n) if Tools.is_perm(n,t) ])

예제 #31
0
import Prime
from time import time

s = time()
print sum(Prime.prime_seive(2000000))

print time() - s

예제 #32
0
import math
import Prime

n = 600851475143


print Prime.factor(n)
예제 #33
0
파일: main.py 프로젝트: linhthi/INT3213
from ElGamal import ElGamal
from base26Cipher import Encrypt
import Prime
from random import randint

# f = open('input.txt')
# np = int(f.readline())
# na = int(f.readline())
# nk = int(f.readline())
# base = f.readline()

base = 'Dexuatcachlyxahoivoinhomdiaphuongnguycocao'

p = 10**99 + 289
a = 10**59 + 1
k = 10**63 + 2
alpha = Prime.primitiveRoot(p)
print(alpha)

# p = Prime.randomPrime(np)
# a = randint(10 ** (na - 1), 10 ** na - 1)
# k = randint(10 ** (nk - 1), 10 ** nk - 1)
# alpha = Prime.primitiveRoot(p)
x = Encrypt(base) % p
print(x)

elGamal = ElGamal(p, a, k)
print(elGamal.beta)
y1, y2 = elGamal.enCode(x)
print((y1, y2))
print(elGamal.deCode(y1, y2))
예제 #34
0
        res = a*1000000 + b
    elif b > 10000:
        res = a*100000 + b
    elif b > 1000:
        res = a*10000 + b
    elif b > 100:
        res = a*1000 + b
    elif b > 10:
        res = a*100 + b
    else:
        res = a*10 + b

    return res

max_n = 99999999
Prime.prime_seive(max_n)
prime_set = set(Prime.primes)
pairs = {}
print "Making pairs"

ttotal = 0
for i in xrange(Prime.n_primes):
    p1 = Prime.primes[i]
    for j in xrange(i+1, Prime.n_primes):
        ttotal += 1
        p2 = Prime.primes[j]
        #if Prime.isPrime(cat_ints(p1,p2)) and Prime.isPrime(cat_ints(p2,p1)):
        new_p1 = cat_ints(p1,p2) 
        if new_p1 in prime_set:
            new_p2 = cat_ints(p2,p1) 
            if new_p2 in prime_set :
예제 #35
0
import Prime

if __name__ == '__main__':
    primes = set(Prime.primes)
    diags = [1]
    nom = 0
    denom = 1
    for i in range(1, 1000000):
        d = i * 2
        denom += 4
        for j in range(4):
            diags.append(diags[-1] + d)
        for num in diags[-4:]:
            if Prime.is_prime(num) == True:
                nom += 1
        #print nom, denom
        if float(nom) / float(denom) < 0.1:
            print d + 1
            break
예제 #36
0
import Prime

#print('Эратосфен в ', Prime2.print_PM_by_Roma(10000, False) / Prime2.print_PM(10000, False), ' раз быстрее')
print(Prime.print_PM(10000, False))
예제 #37
0
#!/usr/bin/python2
import Prime
import math

def corners(max_n):
    for n in xrange(1,max_n+1):
        odd = 2*n+1
        d = 2*n
        for i in xrange(odd**2 - 3*d, odd**2+1, d):
            yield i

n = 13500

Prime.prime_seive((2*n+1)**2)

iprime = 0
n_primes = 0.
total = 0.
for c in corners(n):
    for i in xrange(iprime,Prime.n_primes):
        if Prime.primes[i] == c:
            n_primes += 1.
            break
        elif Prime.primes[i] > c:
            break
    iprime = i

    #pf = Prime.primeFactors(c)
    #if Prime.primeFactors(c).isPrime():
        #n_primes += 1.
    total += 1.
예제 #38
0
파일: Demo.py 프로젝트: sad786/Python
import Prime

Prime.method("")
예제 #39
0
파일: RSA.py 프로젝트: zhexuejia53/RSA
def decryption(secret, prk):
    return Prime.quick_pow_mod(secret, prk[1], prk[0])
예제 #40
0
 def setUp(self):
     self.prime = Prime()
예제 #41
0
파일: RSA.py 프로젝트: zhexuejia53/RSA
def encryption(message, puk):
    return Prime.quick_pow_mod(message, puk[1], puk[0])
예제 #42
0
from Prime import *
from Happy import *
Happy().happyFile()
Prime().primeFile()
overlap = []
happy = open("happy.txt")
prime = open("prime.txt")
happylist = happy.read().split()
primelist = prime.read().split()
for h in happylist:
    for p in primelist:
        if h == p:
            overlap.append(h)
print("The overlapping values in happy numbers and prime numbers are ")
print(", ".join(overlap))
print("The count of overlapping values ranging from 1 to 1000 are",
      len(overlap))
예제 #43
0
import Prime as p
import Reverse as r

for num in range(1, 100):
    if (p.isPrime(num)):
        revNum = r.getReverse(num)
        if (revNum == num): continue
        if (p.isPrime(revNum)): print(num)
예제 #44
0
import numpy as np
import Prime
import matplotlib.pyplot as plt
import streamlit as st

x = st.slider('Select a value', 2, 10000)
Choose = st.radio("With Prime or without", ('Prime', 'Odd', 'All'))

Prime = np.array(Prime.PrimeNum(2, x))

if Choose == 'Prime':
    In = Prime
elif Choose == 'Odd':
    In = np.arange(start=1, stop=x, step=2)
elif Choose == 'All':
    In = np.arange(start=1, stop=x, step=1)

Output = []
for i in In:
    Temp = np.binary_repr(i)
    TempReverse = Temp[::-1]
    T1 = int(Temp, 2)
    T2 = int(TempReverse, 2)
    Output.append(T2 - T1)

if Choose == 'Prime':
    plt.scatter(In, Output, c="blue")
elif Choose == 'Odd':
    plt.scatter(In, Output, c="red")
elif Choose == 'All':
    plt.scatter(In, Output, c="orange")
예제 #45
0
import math
import Prime

lcm = Prime.factor(2)
for i in range(3,21):
   lcm  = lcm.LCM(Prime.factor(i))
   print reduce(lambda x, y: x*y, lcm.getlist())




예제 #46
0
import Prime

n = 1000000
Prime.prime_seive(n)

print max([ (n/float(t),n) for n,t in Prime.totient(n) ])