Пример #1
0
    def eig2(mat):
        a1 = mat[0][0]
        a2 = mat[0][1]
        a3 = mat[1][0]
        a4 = mat[1][1]

        c1 = GSConst.c[1]
        c2 = GSConst.c[2]
        c4 = GSConst.c[4]

        b = -(a1 + a4)
        c = a1*a4 - a2*a3
        d = b*b - c4*c
        l1 = (-b - sqrt(d)) / c2
        l2 = (-b + sqrt(d)) / c2
        k1 = a2 / (l1 - a1)
        k2 = a2 / (l2 - a1)
        v12 = c1 / sqrt(c1 + k1*k1)
        v11 = k1 * v12
        v22 = c1 / sqrt(c1 + k2*k2)
        v21 = k2 * v22
        if norm(l1) < norm(l2):
            return [[[v12, v11], [v22, v21]], [l1, l2]]
        else:
            return [[[v22, v21], [v12, v11]], [l2, l1]]
Пример #2
0
    def factorization(n, delta):
        gmpy2.get_context().precision=1000000
        t = gmpy2.mpz(gmpy2.sqrt(n))
        res = gmpy2.mpfr('0.0', 1000000)
        steps = delta-t
        print "Steps: %d" % steps

        while True:

            res = gmpy2.sqrt(t**2 - n)

            if gmpy2.is_integer(res):
                break
            if res >= n/2:
                sys.stderr.write('I can\'t solve')
                exit()

            t += 1
            steps -= 1
            if steps % 1000 == 0:
                print steps

        p = t - gmpy2.mpz(res)
        q = n/p

        return {
            'p': int(q),
            'q': int(p)
        }
Пример #3
0
 def __init__(self, l_fac, r0):
     self.PI_2 = acos(D0)
     self.ph = self.phDot = D0
     self.r = r0
     self.L = l_fac * sqrt(r0)
     self.L2 = self.L**2
     self.rDot = - sqrt(r0 - self.L2) / self.r
     self.H0 = self.h()
Пример #4
0
def fermat_factor(n):
    assert n % 2 != 0  # Odd integers only

    a = gmpy2.isqrt(n)
    b2 = gmpy2.square(a) - n
    while not is_square(b2):
        a += 1
        b2 = gmpy2.square(a) - n

    factor1 = a + gmpy2.sqrt(b2)
    factor2 = a - gmpy2.sqrt(b2)
    return int(factor1), int(factor2) 
Пример #5
0
def computeN3Factors():
    A = gmpy2.ceil(gmpy2.mul(2, gmpy2.sqrt(gmpy2.mul(6, N3))))
    X = gmpy2.ceil(
        gmpy2.sqrt(
            gmpy2.sub(
                pow(A, 2),
                gmpy2.mul(24, N3)
            )
        )
    )
    p = gmpy2.ceil(gmpy2.div(gmpy2.sub(A, X), 6)) # Only round one.
    q = gmpy2.div(N3, p)
    confirmed(N3, p, q)
Пример #6
0
def q3():
    N = 720062263747350425279564435525583738338084451473999841826653057981916355690188337790423408664187663938485175264994017897083524079135686877441155132015188279331812309091996246361896836573643119174094961348524639707885238799396839230364676670221627018353299443241192173812729276147530748597302192751375739387929

    rt = gmpy2.sqrt(gmpy2.mul(N, 6))
    A = gmpy2.ceil(rt)

    A2 = pow(A, 2)
    assert A2 > N

    x = gmpy2.sqrt(gmpy2.sub(A2, N))
    x = gmpy2.mul(x, 3/2)
    p = gmpy2.sub(A, x)
    q = gmpy2.add(A, x)
    gotcha(N, p, q)
Пример #7
0
def q1():
    N = 179769313486231590772930519078902473361797697894230657273430081157732675805505620686985379449212982959585501387537164015710139858647833778606925583497541085196591615128057575940752635007475935288710823649949940771895617054361149474865046711015101563940680527540071584560878577663743040086340742855278549092581

    rt = gmpy2.sqrt(N)
    A = gmpy2.ceil(rt)
    A2 = pow(A, 2)

    assert A2 > N

    x = gmpy2.sqrt(gmpy2.sub(A2, N))

    p = gmpy2.sub(A, x)
    q = gmpy2.add(A, x)
    gotcha(N, p, q)
Пример #8
0
def FermatFactor(N):
  A = gmpy2.mpz( gmpy2.ceil( gmpy2.sqrt(N) ) )
  B2 = gmpy2.sub( gmpy2.square(A), N )

  while not gmpy2.is_square(B2): 
    A = gmpy2.add( A, gmpy2.mpz("1") )
    B2 = gmpy2.sub( gmpy2.square(A), N )
  
  B = gmpy2.sqrt(B2)
  P = gmpy2.mpz( gmpy2.sub( A, B ) )
  Q = gmpy2.mpz( gmpy2.add( A, B ) )
  if not checkFactors(P,Q,N):
    raise Exception("Bad factors generated")
  return ( P, Q )
def solve_first(N):
  gmpy2.get_context().precision = 1000
  Nsqrt = gmpy2.sqrt(N)
  A = gmpy2.mpz(gmpy2.rint_ceil(Nsqrt))
  A2 = A*A
  x = gmpy2.isqrt(A2 - N)
  print "#1 ----> P is: " + str(A-x)
Пример #10
0
def could_be_prime(n):
   '''Performs some trials to compute whether n could be prime. Run time is O(N^3 / (log N)^2) for N bits.

Returns whether it is possible for n to be prime (True or False).
'''
   if n < 2:
      return False
   if n == 2:
      return True
   if not int(n) & 1:
      return False

   product = ONE
   log_n = int(math.log(n)) + 1
   bound = int(math.log(n) / (LOG_2 * math.log(math.log(n))**2)) + 1
   if bound * log_n >= n:
      bound = 1
      log_n = int(sqrt(n))
   prime_bound = 0
   prime = 3

   for _ in range(bound):
      p = []
      prime_bound += log_n
      while prime <= prime_bound:
         p.append(prime)
         prime = next_prime(prime)
      if p != []:
         p = prod(p)
         product = (product * p) % n

   return gcd(n, product) == 1
Пример #11
0
Файл: PyPi.py Проект: wxv/PiCalc
def chudnovsky(digits):
    # 20 safety digits because lots of calculations (only about 3 are needed)
    scale = 10**(mpz(digits+20))  

    gmpy2.get_context().precision = int(math.log2(10) * (digits + 20)) 
    
    k = mpz(1)
    a_k = scale
    a_sum = scale
    b_sum = mpz(0)
    C = mpz(640320)
    C_cubed_over_24 = C**3 // 24
    
    while True:
        a_k *= -(6*k-5) * (2*k-1) * (6*k-1)
        a_k //= k**3 * C_cubed_over_24
        a_sum += a_k
        b_sum += k * a_k
        k += 1
        if a_k == 0:
            break
    
    total_sum = mpfr(13591409 * a_sum + 545140134 * b_sum)
    pi = (426880 * gmpy2.sqrt(mpfr(10005))) / total_sum
 
    return pi*scale
Пример #12
0
def callfunc2(a, b):
    # print("Number of arguments", emb.numargs())

    gmpy2.get_context().precision = 100
    print(gmpy2.sqrt(5))

    mp.dps = 50
    print(mpf(2) ** mpf("0.5"))

    x = 21.3
    s = "a*x+1 * math.sin(3)"
    result = eval(s)
    print(result)

    mycode = """print ('hello world from mycode')"""

    exec(mycode)

    def f(x):
        x = x + 12
        return x

    print(f(4))

    print("Will compute", a, "times", b)
    c = 0
    for i in range(0, a):
        c = c + b
    return c
Пример #13
0
def main23(N):
    c=gmpy2.context()
    c.precision=len(str(N))+20
    c.real_prec=len(str(N))+20
    gmpy2.set_context(c)
    assert N==gmpy2.mpz(N)
    N=gmpy2.mpz(N)
    A=find_sqrt(6*N)
    A = gmpy2.mpz(A)
    assert ( (A-1)**2<6*N<A**2 ),'not found'
    Atag = A
    for iA in xrange(-2**20,2**20):
        A = Atag + iA
        s =A**2-N
        x = gmpy2.sqrt(s)
        try:
            x = gmpy2.mpz(x)
        except:continue
        '''print x**2 > s ,  x**2 < s
        while x**2>s:
            x-=1
            print 1,
        print x**2 > s ,  x**2 < s'''
        for p in [(A-x)/2,(A-x)/3,(A+x)/2,(A+x)/3   ]:
            q = N/p
            
            if p*q==N:
                print gmpy2.is_prime(q)
                print gmpy2.is_prime(p)
                print min(p,q)
                assert False,'bla'
Пример #14
0
def main(N):
    c=gmpy2.context()
    c.precision=len(str(N))+20
    c.real_prec=len(str(N))+20
    gmpy2.set_context(c)
    assert N==gmpy2.mpz(N)
    N=gmpy2.mpz(N)
    A=find_sqrt(N)
    A = gmpy2.mpz(A)
    assert ( (A-1)**2<N<A**2 ),'not found'
    Atag = A
    for iA in xrange(-2**20,2**20):
        A = Atag + iA
        s =A**2-N
        x = gmpy2.sqrt(s)
        try:
            x = gmpy2.mpz(x)
        except:continue
        print x**2 > s ,  x**2 < s
        '''while x**2>s:
            x-=1
            print 1,'''
        print x**2 > s ,  x**2 < s

        p = A-x
        q = A+x
        q = N/p

        if p*q==N:
            print gmpy2.is_prime(q)
            print gmpy2.is_prime(p)
            print min(p,q)
            break
Пример #15
0
 def solve_quadratic(a, b, c):
     """ Solves the quadratic equation ```a x2 + b x + c = 0```
     :return: the GMP result of solving the quadratic equation usign multi-precision numbers
     """
     bb = sqrt(sub(mul(b, b), mul(mpz(4), mul(a, c))))
     x1 = gmpy2.div(sub(-b, bb), mul(mpz(2), a))
     x2 = gmpy2.div(add(-b, bb), mul(mpz(2), a))
     return x1, x2
Пример #16
0
def Numbers(n):
    i = pow(gmpy2.mpfr(3 + gmpy2.sqrt(5)), n)
    #print(i)
    i = int(gmpy2.rint_trunc(i)) % 1000
    o = i - ((i // 10) * 10)
    t = (i - ((i // 100) * 100) - o) / 10
    h = (i - t - o) / 100
    return str(h)+str(t)+str(o)
Пример #17
0
def Carpenter(p, q,r, s):
	p = gmpy2.mpfr(p)
	q = gmpy2.mpfr(q)
	r = gmpy2.mpfr(r)
	s = gmpy2.mpfr(s)
	"""
	Solves for all roots of the quartic polynomial P(x) = x^4 + px^3 + qx^2 + rx + s.
	"""
	#print "@@@ inside Carpenter", p,q,r,s
	pby4 = p/4.0
	C = ((6 * pby4) - 3*p)*pby4 + q
	D = (((-4*pby4) + 3*p)*pby4 - 2*q)*pby4 + r
	E = (((pby4 - p)* pby4 + q)*pby4 - r)*pby4 + s
	#print "C, D, E=",C, D, E
	root = None
	for zero in polyCubicRoots(2*C, (C**2 - 4*E), -D**2):
		#print "zero = ", zero
		if type(zero)== type(gmpy2.mpfr(1.0)) and zero > 0.0:
		   root = zero
		   #print "found a positive root."
		   break
	if root == None:
		return None
	sqroot = gmpy2.sqrt(root)
	Q1 = -root/4.0 - C/2.0 - D/2.0 / sqroot
	Q2 = -root/4.0 - C/2.0 + D/2.0 / sqroot
	#print "Q1,Q2=", Q1, Q2
	sqy2 = sqroot/2.0
	if Q1 >= 0.0:
	   sqQ1 = gmpy2.sqrt(Q1)
	   z1 = sqy2 + sqQ1 -pby4
	   z2 = sqy2 - sqQ1 -pby4
	else:
	   sqQ1 = gmpy2.sqrt(-Q1)
	   z1 = (sqy2-pby4,   sqQ1)
	   z2 = (sqy2-pby4, - sqQ1)
	if Q2 >= 0.0:
	   sqQ2 = gmpy2.sqrt(Q2)
	   z3 = -sqy2 - sqQ2 -pby4
	   z4 = -sqy2 + sqQ2 -pby4
	else:
	   sqQ2 = gmpy2.sqrt(-Q2)
	   z3 = (-sqy2-pby4, sqQ2)
	   z4 = (-sqy2-pby4, -sqQ2)
	return (z1, z2,z3, z4)
Пример #18
0
 def calc_brute_force(self):
     a = ceil(sqrt(self.n))
     for n in xrange(1, 2 ** 20):
         p, q = self._calc_factors(add(a, n))
         if self._check_sol(p, q):
             return p, q
         #self.log.print_progress(n)
     else:
         raise ValueError("Cannot factor {}".format(self.n))
Пример #19
0
def is_square(integer):
    itg = gmpy2.mpz(integer)
    gmpy2.get_context().precision = 2048
    root = gmpy2.sqrt(itg)
    # root = math.sqrt(integer)
    if int(root) ** 2 == integer:
        return True
    else:
        return False
Пример #20
0
def q2():
    N = 648455842808071669662824265346772278726343720706976263060439070378797308618081116462714015276061417569195587321840254520655424906719892428844841839353281972988531310511738648965962582821502504990264452100885281673303711142296421027840289307657458645233683357077834689715838646088239640236866252211790085787877

    rt = gmpy2.sqrt(N)
    A = gmpy2.ceil(rt)

    q = 0
    p = 0

    while not gotcha(N, p, q):
        A2 = pow(A, 2)
        assert A2 > N

        x = gmpy2.sqrt(gmpy2.sub(A2, N))

        p = gmpy2.sub(A, x)
        q = gmpy2.add(A, x)
        assert N == gmpy2.mul(p, q)
        A += 1
Пример #21
0
def squareroot_test():
    start_timer()
    for i in range(100):
        x = gmpy2.isqrt(3 * scale**2)
    print_timer()
    
    start_timer()
    for i in range(100):
        x = gmpy2.sqrt(gmpy2.mpfr(3))
    print_timer()
Пример #22
0
def main():
    # predefine these, we will stop overwriting them when ready to run the big numbers
    p=mpz('13407807929942597099574024998205846127'
         '47936582059239337772356144372176403007'
         '35469768018742981669034276900318581848'
         '6050853753882811946569946433649006084171'
         )
    g=mpz('117178298803662070095161175963353670885'
         '580849999989522055999794590639294997365'
         '837466705721764714603129285948296754282'
         '79466566527115212748467589894601965568'
        )
    y=mpz('323947510405045044356526437872806578864'
         '909752095244952783479245297198197614329'
         '255807385693795855318053287892800149470'
         '6097394108577585732452307673444020333'
         )

    log.info("Starting Discrete Log Calculation")
    log.info("p: %i", p)
    log.info("g: %i", g)
    log.info("y: %i", y)

    m = gmpy2.ceil(gmpy2.sqrt(p))
    log.info("m: %i", m)

    # custom range since builtin has a size limit
    long_range = lambda start, stop: iter(itertools.count(start).next, stop)
    chunk_size = 100000
    
    if m < 100000:
        chunk_size = m
    
    stop_at = chunk_size
    start = 0

    while True:
        chunk = {}
        log.info("Starting chunk from %i to %i", start, stop_at)
        for i in xrange(start, stop_at):
            chunk[gmpy2.powmod(g,i,p)] = i
        for t in long_range(0,m):
            expone = mpz(gmpy2.mul(-m,t))
            g_term = gmpy2.powmod(g, expone, p)
            res = gmpy2.f_mod(gmpy2.mul(y, g_term), p)
            if res in chunk:
                s = chunk[res]
                dc = gmpy2.f_mod(mpz(gmpy2.add(s, gmpy2.mul(m,t))), p)
                log.info("DC LOG FOUND")
                log.info("dc: %i", dc)
                return
        log.info("Completed chunk run: %i to %i  no DC yet :(", start, stop_at)
        start = stop_at
        stop_at += chunk_size
Пример #23
0
Файл: PyPi.py Проект: wxv/PiCalc
def gauss_legendre(digits):
    gmpy2.get_context().precision = int(math.log2(10) * (digits + 5))
    
    iterations = int(math.log2(digits)) 
    
    # Direct translation of algorithm
    a = mpfr(1)
    b = 1 / gmpy2.sqrt(mpfr(2))
    t = mpfr(1)/4
    x = mpfr(1)


    for i in range(iterations):
        y = a
        a = (a + b) / 2
        b = gmpy2.sqrt(b * y)
        t = t - x * (y-a)**2
        x = 2 * x
        
    pi = ((a+b)**2) / (4*t)
    return pi
Пример #24
0
def computeN2Factors():
    p = 0
    q = 0
    A = computeA(N2)

    while not confirmed(N2, p, q):
        A2 = pow(A, 2)
        assert A2 > N2
        x = gmpy2.sqrt(gmpy2.sub(A2, N2))
        p = gmpy2.sub(A, x)
        q = gmpy2.add(A, x)
        A += 1
Пример #25
0
def default_keylists(*args, **kwargs):
    """Default arg for build_config"""
    size = kwargs.pop('size', None)
    if size is None:
        size = 9
    assert gmpy2.is_square(size), "size must be a square number"
    groupwidth = int(gmpy2.sqrt(size))
    k1 = lambda i, j: i // groupwidth + (j // groupwidth) * groupwidth
    k2 = lambda i, j: i %  groupwidth + (j %  groupwidth) * groupwidth
    return [
        [(k1(i,j),k2(i,j)) for i in range(size)]
            for j in range(size)
    ]
Пример #26
0
def find_sqrt(N):
    n =gmpy2.floor(
                  gmpy2.sqrt(
                             gmpy2.mpfr(N,precision = len(str(N))+50  )
                             )
                  )
    n = gmpy2.mpz(n)
    for i in xrange(-2**10,2**20,1):
        #print (n+i)**2>N
        if (n+i)**2>N:
            print 'found'
            return n+i
    assert False,'bla'
Пример #27
0
Файл: PyPi.py Проект: wxv/PiCalc
def borwein(digits):
    gmpy2.get_context().precision = int(math.log2(10) * (digits + 10))
    
    sqrt_2 = gmpy2.sqrt(mpfr(2))
    a_n = sqrt_2
    b_n = mpz(0)
    p_n = 2 + sqrt_2
    
    while True:
        sqrt_a_n = gmpy2.sqrt(a_n)
        a_n1 = (sqrt_a_n + 1/sqrt_a_n) / 2
        b_n1 = (1 + b_n) * sqrt_a_n / (a_n + b_n)
        p_n1 = (1 + a_n1) * p_n * b_n1 / (1 + b_n1)
        
        if p_n1 == p_n:
            break
        
        a_n = a_n1
        b_n = b_n1
        p_n = p_n1
        
    return p_n
Пример #28
0
 def __init__(self, cc, a, mu2, e, l, q, r0, th0, xh):
     self.l_3 = cc / D3
     self.a = a
     self.mu2 = mu2
     self.E = e
     self.L = l
     self.a2 = a**2
     self.a2l_3 = self.a2 * self.l_3
     self.a2mu2 = self.a2 * mu2
     self.aE = a * e
     self.aL = a * l
     self.X2 = (D1 + self.a2l_3)**2
     self.two_EX2 = D2 * e * self.X2
     self.two_aE = D2 * a * e
     self.K = q + self.X2 * (l - self.aE)**2
     self.t = self.ph = D0
     self.r = r0
     self.th = (mpfr("90.0") - th0) * acos(mpfr("-1")) / mpfr("180.0")
     self.cross = xh
     self.refresh()
     self.Ur = - sqrt(self.r_potential if self.r_potential >= D0 else -self.r_potential)
     self.Uth = - sqrt(self.th_potential if self.th_potential >= D0 else -self.th_potential)
Пример #29
0
def fairsquare(a, b):
    import gmpy2
    global fns
    ans = 0
    for i in xrange(a, b + 1):
        if i in fns:
            ans += 1
        else:
            if is_palindrome(i):
                if gmpy2.is_square(i):
                    s = int(gmpy2.sqrt(i))
                    if is_palindrome(s):
                        fns.add(i)
                        ans += 1
    return ans
Пример #30
0
 def findFactorsCaseTwo(self):
     print("===========================================")
     print("Modulus N is: " + str(self.N))
     #A = (p+q)/2 AND A can be any where from ceil(sqrt(N)) to ceil(sqrt(N)) + 2 ^ 20
     A = gmpy2.ceil(gmpy2.sqrt(self.N))
     print("A is: " + str(A))
     upperRange = 2 ** 20
     for index in range (0, upperRange + 1):
         #x = sqrt(A^2 - N)
         A_square = gmpy2.mul(A, A)
         diff = gmpy2.sub(A_square, self.N)
         x = mpz(gmpy2.sqrt(diff))
         #p = A - x AND q = A + x
         self.p = gmpy2.sub(A, x)
         self.q = gmpy2.add(A, x)
         prod = gmpy2.mul(self.p, self.q)
         if prod == self.N:
             print("We have got the factors RIGHT")
             return
         else:
             A = A + 1
     print("We didn't get the factors")
     self.p = 0
     self.q = 0
Пример #31
0
 def findFactorsCaseOne(self):
     print("===========================================")
     print("Modulus N is: " + str(self.N))
     #A = (p+q)/2 == ceil(sqrt(N))
     A = gmpy2.ceil(gmpy2.sqrt(self.N))
     print("A is: " + str(A))
     #x = sqrt(A^2 - N)
     A_square = gmpy2.mul(A, A)
     x = gmpy2.sqrt(gmpy2.sub(A_square, self.N))
     print("x is: " + str(x))
     #p = A - x AND q = A + x
     self.p = gmpy2.sub(A, x)
     self.q = gmpy2.add(A, x)
     prod = gmpy2.mul(self.p, self.q)
     print("Product of pq is: " + str(prod))
     if prod == self.N:
         print("We have got the factors RIGHT")
     else:
         print("We didn't get the factors")
         print(self.p)
         print(self.q)
         self.p = 0
         self.q = 0
     print("===========================================")
Пример #32
0
def findpq(d, e, N):
    ed = e * d
    gmpy2.get_context().precision=10000
    # my_ed * d = phi(n) * k + 1
    # print (my_e * d - 1) # <-- this is a multiple of phi(n)
    # the range is 1 -> e for k 
    p = -1
    q = -1
    for k in range(1, e):
        temp = (ed-1)
        if temp % k == 0:
            temp //= k # phi(n) possibility
            p_plus_q = N + 1 - temp
            # ((p+q) + sqrt((p+q)2 - 4*pq))/2
            sqrt_check = gmpy2.is_square( pow(p_plus_q, 2) - 4 * N)
            if sqrt_check == True:
                # p = ((p+q) + sqrt((p+q)2 - 4*pq))/2
                # q = ((p+q) - sqrt((p+q)2 - 4*pq))/2
                p = (p_plus_q + gmpy2.sqrt( pow(p_plus_q, 2) - 4 * N)) //2
                p = int(p)
                q = (p_plus_q - gmpy2.sqrt( pow(p_plus_q, 2) - 4 * N)) //2
                q = int(q)

    return p, q
Пример #33
0
def main():

    # 2; used alpertron to factor n
    n = 742449129124467073921545687640895127535705902454369756401331
    e = 3
    ct = 39207274348578481322317340648475596807303160111338236677373
    p = 752708788837165590355094155871
    q = 986369682585281993933185289261
    phi = (p - 1) * (q - 1)
    d = gmpy2.invert(e, phi)
    plain = pow(ct, d, n)
    print(trans(plain))

    # 3:
    n = 171731371218065444125482536302245915415603318380280392385291836472299752747934607246477508507827284075763910264995326010251268493630501989810855418416643352631102434317900028697993224868629935657273062472544675693365930943308086634291936846505861203914449338007760990051788980485462592823446469606824421932591
    e = 65537
    ct = 161367550346730604451454756189028938964941280347662098798775466019463375610700074840105776873791605070092554650190486030367121011578171525759600774739890458414593857709994072516290998135846956596662071379067305011746842247628316996977338024343628757374524136260758515864509435302781735938531030576289086798942
    phi = n - 1
    d = gmpy2.invert(e, phi)
    plain = pow(ct, d, n)
    print(trans(plain))

    # 4:
    N = 535860808044009550029177135708168016201451343147313565371014459027743491739422885443084705720731409713775527993719682583669164873806842043288439828071789970694759080842162253955259590552283047728782812946845160334801782088068154453021936721710269050985805054692096738777321796153384024897615594493453068138341203673749514094546000253631902991617197847584519694152122765406982133526594928685232381934742152195861380221224370858128736975959176861651044370378539093990198336298572944512738570839396588590096813217791191895941380464803377602779240663133834952329316862399581950590588006371221334128215409197603236942597674756728212232134056562716399155080108881105952768189193728827484667349378091100068224404684701674782399200373192433062767622841264055426035349769018117299620554803902490432339600566432246795818167460916180647394169157647245603555692735630862148715428791242764799469896924753470539857080767170052783918273180304835318388177089674231640910337743789750979216202573226794240332797892868276309400253925932223895530714169648116569013581643192341931800785254715083294526325980247219218364118877864892068185905587410977152737936310734712276956663192182487672474651103240004173381041237906849437490609652395748868434296753449
    e = 65537
    c = 222502885974182429500948389840563415291534726891354573907329512556439632810921927905220486727807436668035929302442754225952786602492250448020341217733646472982286222338860566076161977786095675944552232391481278782019346283900959677167026636830252067048759720251671811058647569724495547940966885025629807079171218371644528053562232396674283745310132242492367274184667845174514466834132589971388067076980563188513333661165819462428837210575342101036356974189393390097403614434491507672459254969638032776897417674577487775755539964915035731988499983726435005007850876000232292458554577437739427313453671492956668188219600633325930981748162455965093222648173134777571527681591366164711307355510889316052064146089646772869610726671696699221157985834325663661400034831442431209123478778078255846830522226390964119818784903330200488705212765569163495571851459355520398928214206285080883954881888668509262455490889283862560453598662919522224935145694435885396500780651530829377030371611921181207362217397805303962112100190783763061909945889717878397740711340114311597934724670601992737526668932871436226135393872881664511222789565256059138002651403875484920711316522536260604255269532161594824301047729082877262812899724246757871448545439896
    gmpy2.get_context().precision = 10000
    p = int(gmpy2.sqrt(N))
    # print(p)
    phi = (p - 1) * (p)
    d = gmpy2.invert(e, phi)
    plain = pow(c, d, N)
    print(trans(plain))

    # 5:
    n = 580642391898843192929563856870897799650883152718761762932292482252152591279871421569162037190419036435041797739880389529593674485555792234900969402019055601781662044515999210032698275981631376651117318677368742867687180140048715627160641771118040372573575479330830092989800730105573700557717146251860588802509310534792310748898504394966263819959963273509119791037525504422606634640173277598774814099540555569257179715908642917355365791447508751401889724095964924513196281345665480688029639999472649549163147599540142367575413885729653166517595719991872223011969856259344396899748662101941230745601719730556631637
    e = 65537
    ct = 320721490534624434149993723527322977960556510750628354856260732098109692581338409999983376131354918370047625150454728718467998870322344980985635149656977787964380651868131740312053755501594999166365821315043312308622388016666802478485476059625888033017198083472976011719998333985531756978678758897472845358167730221506573817798467100023754709109274265835201757369829744113233607359526441007577850111228850004361838028842815813724076511058179239339760639518034583306154826603816927757236549096339501503316601078891287408682099750164720032975016814187899399273719181407940397071512493967454225665490162619270814464
    # factoring done using alpertron
    temp = "9 282105 380008 121879 × 9 303850 685953 812323 × 9 389357 739583 927789 × 10 336650 220878 499841 × 10 638241 655447 339831 × 11 282698 189561 966721 × 11 328768 673634 243077 × 11 403460 639036 243901 × 11 473665 579512 371723 × 11 492065 299277 279799 × 11 530534 813954 192171 × 11 665347 949879 312361 × 12 132158 321859 677597 × 12 834461 276877 415051 × 12 955403 765595 949597 × 12 973972 336777 979701 × 13 099895 578757 581201 × 13 572286 589428 162097 × 14 100640 260554 622013 × 14 178869 592193 599187 × 14 278240 802299 816541 × 14 523070 016044 624039 × 14 963354 250199 553339 × 15 364597 561881 860737 × 15 669758 663523 555763 × 15 824122 791679 574573 × 15 998365 463074 268941 × 16 656402 470578 844539 × 16 898740 504023 346457 × 17 138336 856793 050757 × 17 174065 872156 629921 × 17 281246 625998 849649"
    factors = temp.split("×")
    factors = [int(i.replace(" ", "")) for i in factors]
    phi = 1
    for i in factors:
        phi *= (i - 1)
    d = gmpy2.invert(e, phi)
    plain = pow(ct, d, n)
    print(trans(plain))
Пример #34
0
def test(m):
    rx, ry = mpfr(0), mpfr(0)
    for M in P:
        dx = m[0] - M[0]
        dy = m[1] - M[1]

        if dx == 0 and dy == 0:
            continue

        dist = gmpy2.sqrt(dx**2 + dy**2)
        forc = force(M, m)
        rate = forc / dist
        rx += dx * rate
        ry += dy * rate

    return (rx, ry)
Пример #35
0
        def b_genNext():
            '''
			b(n+1)
			'''
            # Variables
            nonlocal b
            nonlocal a_n

            # To be updated
            nonlocal b_n
            nonlocal b_np1

            # Iteration
            b_n = b
            b = ((1 + b_n) * (sqrt(a_n))) / (a_n + b_n)
            b_np1 = b
Пример #36
0
def pollard_rho(n, process_id):
    i = 1
    # set the point in which rho starts
    if gmpy2.bit_length(gmpy2.mpz(n)) < RHO_CONSTANT:
        # small value modulo so we are better off starting with small value
        if DEBUG:
            print("bit size", gmpy2.bit_length(gmpy2.mpz(n)), "less than",
                  RHO_CONSTANT, "so non ran")
        initial = process_id + 2
        re_rand = False
    else:
        # small value modulo so we are better off starting with a random value
        if DEBUG:
            print("ran")
        # set a flag so we can re rand rho at a latter point
        re_rand = True
        # process_id + 2  # this could also be random.randomint(0, n - 1)
        initial = random.randint(primes[len(primes) - 1],
                                 n // (process_id + 2))
    if DEBUG:
        processLock.acquire()
        print("CORE", process_id, "checking rho of", initial)
        processLock.release()
    y = initial
    k = 2
    previous = initial
    count = 0
    while True:
        i += 1
        count += 1
        # alt methods
        # gmpy2.powmod(pow(previous, 2) - 1, 1, n)  # ((pow(previous, 2)) - 1) % n  #
        current = (((previous**2) - 1) % n)
        d = gmpy2.gcd(y - current, n)
        # check to see if we've found the terminating conditions for rho and we've found a factor
        if d != 1 and d != n:
            return d
        if i == k:
            y = current
            k = 2 * k
        previous = current
        # check to see if we are in random mode and if we need to re random
        if re_rand and count > 100000:  # (gmpy2.sqrt(n) // primes[len(primes)-1]):
            # print("RE-RAN")
            count = 0
            previous = random.randint(primes[len(primes) - 1],
                                      int(gmpy2.sqrt(n)))
Пример #37
0
def icosahedron_vertices():
    zero = gmpy2.zero()
    one = gmpy2.mpfr(1)
    phi = (gmpy2.sqrt(5) + 1) / 2
    return (
        (+one, +phi, zero),
        (+one, -phi, zero),
        (-one, +phi, zero),
        (-one, -phi, zero),
        (zero, +one, +phi),
        (zero, +one, -phi),
        (zero, -one, +phi),
        (zero, -one, -phi),
        (+phi, zero, +one),
        (+phi, zero, -one),
        (-phi, zero, +one),
        (-phi, zero, -one))
Пример #38
0
def cracker(N, root):
    """ 
    We know that N = p*q --> N = (a+b)*(a-b) <=> N = a^2 - b^2 from fermat's factorization method
    Thus, b^2 = a^2 - N. Now, We discovered that Primes generated by the getPrimes method above
    Always generates primes that are symmetric around one of the modular square root of N modulo 2^1024.
    The choosen root shall always satisfy the condition root^2 > N. 
    Thus, we can have a = root, and b as the deviation from a to give p and q
    Thus, b = sqrt(a^2 - N) given (a^2 - N) is a perfect square
    """
    bsquare = root**2 - N
    if bsquare < 0:
        return 0, 0
    b = gmpy2.sqrt(root**2 - N)
    if int(b)**2 != int(bsquare):
        return 0, 0
    p = int(root + b)
    q = int(root - b)
    return p, q
Пример #39
0
 def crack(self):
     for cvg in cf2cvg(f2cf(self.e, self.n)):
         k = cvg.numerator
         if k == 0:
             continue
         d = cvg.denominator
         phi = (self.e * d - 1) // k
         nb = self.n - phi + 1
         squ = nb * nb - 4 * self.n
         if squ < 0:
             continue
         root = gmpy.sqrt(squ)
         if root * root == squ and not (nb + root) & 1:
             self.p = (nb + root) >> 1
             self.q = (nb - root) >> 1
             self.d = d
             return True
     return False
Пример #40
0
def naive(number):
    if number == 2:
        return True
    if number % 2 == 0 or number < 2:
        return False

    i = 3

    rooted = gmpy2.floor(gmpy2.sqrt(number))
    print rooted
    while i <= rooted:
        if number % i == 0:
            return False
        i += 2
        if i % 10000000 == 1:
            print i

    return True
Пример #41
0
def factor(n, s):
    r = 0.5
    while r < 4.5:
        a = 0.8
        while a < 1.1:
            old_p = 0
            p = s
            i = 0
            while abs(p - old_p) > 0.00001 and i < 20 and p < sqrt(n):
                old_p = p
                p = iter(old_p, n, r, a)
                i += 1
            if abs(p - old_p) <= 0.00001:
                #print('{}'.format(int(p)))
                return True
            a += 0.005
        r += 0.1
    return False
Пример #42
0
 def checkPQDistance(self, keys):
     if not isinstance(keys, (tuple, list)):
         keys = [keys]
     ctx = gmpy2.get_context()
     ctx.precision = 5000
     ctx.round = gmpy2.RoundDown
     ctx.real_round = gmpy2.RoundDown
     gmpy2.set_context(ctx)
     for key in keys:
         gmpy_key = gmpy2.mpfr(key)
         skey = int(gmpy2.sqrt(gmpy_key))
         skey2 = skey**2
         if (skey2 > key) or (((skey + 1)**2) < key):
             print skey2
             print(skey + 1)**2
             raise Exception("WTF")
         bits = int(gmpy2.log2(key - skey2))
         if bits < 480:
             print '%d Has p, q distance of %d bits' % (key, bits)
Пример #43
0
def synapsegrow(synapse):
    global memories
    fish = len(memories)
    for x in range(fish):
        if type(synapse[x]) != np.ndarray:
            p = 0
        else:
            p = len(synapse[x])
        q = len(memories[x])
        pq = int(q - p)
        rtq = len(memories[x])
        for y in range(pq):
            init = np.random.randn()
            init *= mp.sqrt(2 / rtq) * init
            ainit = np.array([init], dtype=object)
            if type(synapse[x]) != np.ndarray:
                synapse[x] = ainit
            else:
                synapse[x] = np.append(synapse[x], ainit)
    return synapse
Пример #44
0
def factors2(n):
    n = gmpy2.mpz(n)
    init_guess = gmpy2.isqrt(n)
    A = init_guess
    #    print('intial guess:')
    #    print(guess)
    #print('N2/guess:\n'+ str(int(N2/guess)) + '\nN2%guess:\n'+ str(int(N2%guess)))
    mindiv = n
    for i in range(1048576):
        x = gmpy2.sqrt(A**2 - n)
        p = A - x
        q = A + x
        mod = gmpy2.fmod(n, p)
        div = gmpy2.div(n, p * q)
        if div < mindiv:
            mindiv = div
        if not mod:
            print('p:\n' + str(int(p)))
            print('q:\n' + str(int(q)))
            break
        A += 1
Пример #45
0
    def _house(self):
        """Householder reflection, defined for column vector shapes x=(m,1).
        Returns (v, beta), where v is a column vector v with v[0]=1,
        and the matrix P = I - beta * v * v.T gives the Householder
        transformation satisfying: Px = norm(x)*e_1.
        
        Context: recall that a Householder transformation is given by an
        m-by-m matrix of the form: P = I - beta * v * v.T
        It reflects over v, the Householder vector.
        
        The matrix is never explicitly formed.
        Further info: algorithm 5.1.1, pg 236, Matrix Computations (4th ed).
        
        To efficiently apply the transformation to a matrix:

        PA = A - (beta * v) (v.T * A)
        AP = A - (A*v) (B*v).T
        """
        m, n = self.shape
        assert n == 1, "need shape (m,1); have ({}, {})".format(m, n)
        alpha = self[0, 0]
        y = self[1:]

        sigma = y.frob_prod(y)  #norm squared

        if sigma == 0:
            return self, 0
        else:
            v = self.copy()
            mu = gmpy2.sqrt(alpha**2 + sigma)  # always positive
            if alpha <= 0:
                new_v0 = alpha - mu
            else:
                new_v0 = -sigma / (alpha + mu)
            beta = 2 * new_v0**2 / (sigma + new_v0**2)
            v[(0, 0)] = new_v0
            v /= new_v0
            return v, beta
Пример #46
0
def get_matrix_from_data_file():
    matrix = list()

    # 读取所有乘客的坐标
    with open("passenger.txt", "r") as f:
        passengers = [x.rstrip() for x in f.readlines()]

    # 读取所有司机的坐标
    with open("ubercar.txt", "r") as f:
        cars = [x.rstrip() for x in f.readlines()]

    # 计算并存在矩阵中
    for each_passenger in passengers:
        x1, y1 = each_passenger.split(" ")
        x1, y1 = gmpy2.mpz(float(x1)), gmpy2.mpz(float(y1))
        cost_line = list()
        for each_car in cars:
            x2, y2 = each_car.split(" ")
            x2, y2 = float(x2), float(y2)
            cost = gmpy2.sqrt((x1 - x2)**2 + (y1 - y2)**2)
            cost_line.append(cost)
        matrix.append(cost_line)

    return matrix
Пример #47
0
import gmpy2
from Crypto.Util.number import inverse

gmpy2.get_context().precision = 4096

n = 3332188378295875783869064122703412230143264268626208625352231809707004626253693498892823264566220909462343272078555847886616528581762042090546179170482236487869003184706780657600698382325015809116744248893806650852223735783470295773006852652525553466007962717720284304724619241395637108961365171979649
e = 65537
ct = 3316983025788692017396821771835311006322014015027406970602003270080890623639030751135640062117695237676733971772109533247669892340663705733239749827632105244781062716356677792105791119992377197378659424691710778109509477222535640626877439474417447571477422236539760920897186204634495349674479974912987
p = int(gmpy2.sqrt(n))
phi = n - p
d = inverse(e, phi)

pt = pow(ct, d, n)
hex_pt = hex(pt)
flag = bytes.fromhex(hex_pt[2:])
print(flag)
Пример #48
0
import gmpy2

T = int(raw_input()) + 1

for i in range(1, T):

    line = raw_input()
    [A, B] = line.split(' ')
    A = int(A)
    B = int(B)
    fairsquare = 0

    for x in range(A, B + 1):
        if gmpy2.is_square(x) and str(x) == str(x)[::-1]:
            root = int(gmpy2.sqrt(x))
            if str(root) == str(root)[::-1]:
                fairsquare = fairsquare + 1

    print 'Case #' + str(i) + ': ' + str(fairsquare)
Пример #49
0
def break_primes(n, process_id, sync, output):
    # check to see if the primes were the same
    gmpy2.get_context().precision = 4096
    n_sqrt = gmpy2.sqrt(n)
    # check to see if the modulo is a perfect square root of itself
    if n_sqrt % 1 == 0.0:
        processLock.acquire()
        if output.empty():
            output.put(n_sqrt)
            sync.set()
            print("Duplicate primes detected! Prime is", n_sqrt)
        processLock.release()
        return n_sqrt

    # trial division
    processLock.acquire()
    # loop through the trivial primes
    for i in range(len(primes)):
        # check if we've haven't found anything yet
        if output.empty():
            # the smaller of any factors of modulo has to be less than the sqrt of that modulo so we can give up if we
            # haven't found anything by then
            if primes[i] > gmpy2.sqrt(n):
                break
            elif gmpy2.f_mod(n, primes[i]) == 0.0:
                # share the result and handle the multiprocessing cleanup
                print("Trial Division Success! Divisible by", primes[i])
                print("Result is", n // primes[i])
                output.put(primes[i])
                sync.set()
                # processLock.release()
                return primes[i]
    processLock.release()
    # informative statements
    if DEBUG:
        print("No Trivial")
        print("nothing easy :(")

    # check to see if the modulo is vulnerable to pollard p - 1
    p1_result = pollard_p1(n, process_id)
    processLock.acquire()
    if p1_result > 1 and output.empty():
        # share the result and handle the multiprocessing cleanup
        print(process_id, "p1 factor found:", p1_result)
        output.put(p1_result)
        sync.set()
        return p1_result
    if DEBUG:
        print(process_id, ": p1 no factors")
    processLock.release()

    # check to see if the modulo is vulnerable to william p + 1
    william = 1  # william_p1(n, process_id)
    processLock.acquire()
    if william > 1 and output.empty():
        # share the result and handle the multiprocessing cleanup
        print("William factor found:", william)
        output.put(william)
        sync.set()
        return william
    if DEBUG:
        print(process_id, ": william no factors")
    processLock.release()

    # if all else fails try pollard rho on it
    rho_result = pollard_rho(n, process_id)
    processLock.acquire()
    if output.empty():
        # share the result and handle the multiprocessing cleanup
        print(process_id, "rho factor found:", rho_result)
        output.put_nowait(rho_result)
        sync.set()
    # processLock.release()
    return rho_result
Пример #50
0
# brew install gmp
# brew install mpfr
# brew install libmpc
# bin/easy_install http://gmpy.googlecode.com/files/gmpy2-2.0.0b1.zip
# wget http://www.math.umbc.edu/~campbell/Computers/Python/numbthy.py

from __future__ import division  # division with floats

import gmpy2

gmpy2.get_context().precision = 1100

N = 179769313486231590772930519078902473361797697894230657273430081157732675805505620686985379449212982959585501387537164015710139858647833778606925583497541085196591615128057575940752635007475935288710823649949940771895617054361149474865046711015101563940680527540071584560878577663743040086340742855278549092581

A = gmpy2.ceil(gmpy2.sqrt(N))
A2 = A**2

print "N    :", int(N)
print "sq(A): %.f" % gmpy2.sqrt(N)
print "round:", int(gmpy2.ceil(gmpy2.sqrt(N)))
print "A^2  :", int(A2)

assert A2 > N

x = gmpy2.sqrt(A2 - N)
print "x    :", int(x)

p = gmpy2.sub(A, x)
q = gmpy2.add(A, x)

print "p*q  :", int(gmpy2.mul(p, q))
Пример #51
0
 def fp_sqrt(self) -> 'FPVector':
     return type(self)(gmpy2.sqrt(self._value))
Пример #52
0
    dat = in_file.readline().strip().split()
    d = mpfr(dat[0])
    n = int(dat[1])
    a = int(dat[2])

    this_time, this_pos = map(mpfr, in_file.readline().strip().split())
    last_time, last_pos = this_time, this_pos
    car_time = 0.0
    inp_count = 1
    while this_pos < d:
        last_time, last_pos = this_time, this_pos
        dat = in_file.readline().strip().split()
        this_time, this_pos = map(mpfr, dat)
        inp_count += 1
        if this_pos >= d:
            spd = (this_pos - last_pos) / (this_time - last_time)
            car_time = (d - last_pos) / spd + last_time
            break
    while inp_count < n:
        in_file.readline()
        inp_count += 1
    a_data = map(mpfr, in_file.readline().strip().split())
    pp('Case #' + str(case) + ':')
    for acc in a_data:
        opt_time = sqrt(2.0 * d / acc)
        #        print opt_time, car_time
        pp(str(max(opt_time, car_time)))

out_file.close()
in_file.close()
import gmpy2
gmpy2.get_context().precision=100 # in bits

min_delta = 1e-20

# this implementation assumes the signs for a and b and sometimes fails
print(f"Finding n s.t. (√2-1)^n < min_delta")
n = 0
while (gmpy2.sqrt(2) - 1)**n > min_delta: n += 1
print(f"n: {n}")
print((gmpy2.sqrt(2) - 1)**n)
print(50*'-')

print(f"Simplifying (√2-1)^n to a√2 - b")
simplified = sympy.expand((sympy.sqrt(2)-1)**n)
a, b = simplified.args[1].args[0], -1*simplified.args[0]
print(f"a={a}, b={b}")
print(50*'-')

print("Factoring a and b into their binary representations")
def two_powers(num): return [i for i, bit in enumerate(bin(num)[:1:-1]) if bit == "1"]
a_powers, b_powers = two_powers(a), two_powers(b)
print(f'''a: {a} = {' + '.join([f"2^{x}" for x in a_powers])}''')
print(f'''b: {b} = {' + '.join([f"2^{x}" for x in b_powers])}''')
print(50*'-')

print("Forming and outputting the smooth sets A and B")
A = [2**(2*x+1) for x in a_powers]
B = [2**(2*x) for x in b_powers]
print(f'''A: {', '.join([f"2^{2*x+1}" for x in a_powers])}''')
print(f'''B: {', '.join([f"2^{2*x}" for x in b_powers])}''')
Пример #54
0
def isqrt(n):
    n = gmpy2.mpz(n)
    x = gmpy2.sqrt(n)
    return int(x)
def smooth_sum(nums): return sum(gmpy2.sqrt(x) for x in nums)
print(smooth_sum(A) - smooth_sum(B))
Пример #56
0
import math
import gmpy2

N = gmpy2.mpz(
    E8953849F11E932E9127AF35E1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000051F8EB7D0556E09FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBAD55
)

gmpy2.get_context().precision = 2048
a = int(gmpy2.sqrt(n))

a2 = a * a
b2 = gmpy2.sub(a2, N)

while not (gmpy2.is_square(b2)):
    a = a + 1
    b2 = a * a - N

b2 = gmpy2.mpz(b2)
gmpy2.get_context().precision = 2048
b = int(gmpy2.sqrt(b2))

print a + b

print a - b
Пример #57
0
from gmpy2 import context, set_context
from gmpy2 import mpfr, sqrt, const_pi, exp, sin, cos, polar, norm

import matplotlib.pyplot as plt
from seaborn import set_style

# ------------------------------------------------
### DEFINITIONS ###

set_style('darkgrid')

bits = 64
set_context(context(precision=bits, allow_complex=True))

I = sqrt(-1)

pi = const_pi(bits)

# ------------------------------------------------
### FUNCTIONS ###


def backf(val, digits=8):
    return [backf(v, digits)
            for v in val] if isinstance(val,
                                        (list, tuple, map,
                                         zip)) else float(round(val, digits))


def fourier(func, dt, freq_max):
Пример #58
0
def mainloop(n, u, p1):
   ''' Input:   n  -- an integer to (try) to factor.
         u  -- the phase 1 smoothness bound
         p1 -- a list of sigma parameters to try

   Output:   A factor of n. (1 is returned on faliure).

   Notes:
      1. Other parameters, such as the phase 2 smoothness bound are selected by the mainloop function.
      2. This function uses batch algorithms, so if p1 is not long enough, there will be a loss in efficiency.
      3. Of course, if p1 is too long, then the mainloop will have to use more memory.
           [The memory is polynomial in the length of p1, log u, and log n].'''
   k = inv_const(n)
   log_u = math.log(u)
   log_log_u = math.log(log_u)
   log_n = math.log(n)
   u2 = int(_7_OVER_LOG_2 * u * log_u / log_log_u)
   ncurves = len(p1)
   w = int(math.sqrt(_3_OVER_LOG_2 * ncurves / k) - 0.5)
   number_of_primes = int((ncurves << w) * math.sqrt(LOG_4_OVER_9 * log_n / k) / log_u) # Lagrange multipliers!
   number_of_primes = min(number_of_primes, int((log_n / math.log(log_n))**2 * ncurves / log_u), int(u / log_u))
   number_of_primes = max(number_of_primes, 1)
   m = math.log(number_of_primes) + log_log_u
   w = min(w, int((m - 2 * math.log(m) + LOG_3_MINUS_LOG_LOG_2) / LOG_2))
   w = max(w, 1)
   max_order = n + sqrt(n << 2) + 1 # By Hasse's theorem.
   det_bound = ((1 << w) - 1 + ((w & 1) << 1)) / 3
   log_mo = math.log(max_order)
   p = range(number_of_primes)
   prime = mpz(2)

   p1 = get_points(p1, n)
   if not isinstance(p1, list):
      return p1

   for _ in xrange(int(log_mo / LOG_2)):
      p1 = double(p1, n)
      if not isinstance(p1, list):
         return p1

   for i in xrange(1, det_bound):
      prime  = (i << 1) + 1
      if isprime(prime):
         for _ in xrange(int(log_mo / math.log(prime))):
            p1 = multiply(p1, prime, n)
            if not isinstance(p1, list):
               return p1

   while prime < sqrt(u) and isinstance(p1, list):
      for i in xrange(number_of_primes):
         prime = next_prime(prime)
         p[i] = prime ** max(1, int(log_u / math.log(prime)))
      p1 = fast_multiply(p1, prod(p),  n, w)

   if not isinstance(p1, list):
      return p1

   while prime < u and isinstance(p1, list):
      for i in xrange(number_of_primes):
         prime = next_prime(prime)
         p[i] = prime
      p1 = fast_multiply(p1, prod(p),  n, w)

   if not isinstance(p1, list):
      return p1

   del p

   small_jump = int(greatest_n((1 << (w + 2)) / 3))
   small_jump = max(120, small_jump)
   big_jump = 1 + (int(sqrt((5 << w) / 21)) << 1)
   total_jump = small_jump * big_jump
   big_multiple = max(total_jump << 1, ((int(next_prime(prime)) - (total_jump >> 1)) / total_jump) * total_jump)
   big_jump_2 = big_jump >> 1
   small_jump_2 = small_jump >> 1
   product = ONE

   psmall_jump = multiply(p1, small_jump, n)
   if not isinstance(psmall_jump, list):
      return psmall_jump

   ptotal_jump = multiply(psmall_jump, big_jump, n)
   if not isinstance(ptotal_jump, list):
      return ptotal_jump

   pgiant_step = multiply(p1, big_multiple, n)
   if not isinstance(pgiant_step, list):
      return pgiant_step

   small_multiples = [None]
   for i in xrange(1, small_jump >> 1):
      if gcd(i, small_jump) == 1:
         tmp = multiply(p1, i, n)
         if not isinstance(tmp, list):
            return tmp
         for i in xrange(len(tmp)):
            tmp[i] = tmp[i][0]
         small_multiples.append(tuple(tmp))
      else:
         small_multiples.append(None)
   small_multiples = tuple(small_multiples)

   big_multiples = [None]
   for i in xrange(1, (big_jump + 1) >> 1):
      tmp = multiply(psmall_jump, i, n)
      if not isinstance(tmp, list):
         return tmp
      big_multiples.append(to_tuple(tmp))
   big_multiples = tuple(big_multiples)

   psmall_jump = to_tuple(psmall_jump)
   ptotal_jump = to_tuple(ptotal_jump)

   while big_multiple < u2:
      big_multiple += total_jump
      center_up = big_multiple
      center_down = big_multiple
      pgiant_step = add(ptotal_jump, pgiant_step, n)
      if not isinstance(pgiant_step, list):
         return pgiant_step

      prime_up = next_prime(big_multiple - small_jump_2)
      while prime_up < big_multiple + small_jump_2:
         s = small_multiples[abs(int(prime_up) - big_multiple)]
         for j in xrange(ncurves):
            product *= pgiant_step[j][0] - s[j]
            product %= n
         prime_up = next_prime(prime_up)

      for i in xrange(1, big_jump_2 + 1):
         center_up += small_jump
         center_down -= small_jump

         pmed_step_up, pmed_step_down = add_sub_x_only(big_multiples[i], pgiant_step, n)
         if pmed_step_down == None:
            return pmed_step_up

         while prime_up < center_up + small_jump_2:
            s = small_multiples[abs(int(prime_up) - center_up)]
            for j in xrange(ncurves):
               product *= pmed_step_up[j] - s[j]
               product %= n
            prime_up = next_prime(prime_up)

         prime_down = next_prime(center_down - small_jump_2)
         while prime_down < center_down + small_jump_2:
            s = small_multiples[abs(int(prime_down) - center_down)]
            for j in xrange(ncurves):
               product *= pmed_step_down[j] - s[j]
               product %= n
            prime_down = next_prime(prime_down)

   if gcd(product, n) != 1:
      return gcd(product, n)

   return 1
Пример #59
0
def sub_sub_sure_factors(f, u, curve_parameter):
   '''Finds all factors that can be found using ECM with a smoothness bound of u and sigma and give curve parameters. If that fails, checks for being a prime power and does Fermat factoring as well.

Yields factors.'''
   while not (f & 1):
      yield 2
      f >>= 1

   while not (f % 3):
      yield 3
      f /= 3

   if isprime(f):
      yield f
      return

   log_u = math.log(u)
   u2 = int(_7_OVER_LOG_2 * u * log_u / math.log(log_u))
   primes = []
   still_a_chance = True
   log_mo = math.log(f + 1 + sqrt(f << 2))

   g = gcd(curve_parameter, f)
   if g not in (1, f):
      for factor in sub_sub_sure_factors(g, u, curve_parameter):
         yield factor
      for factor in sub_sub_sure_factors(f/g, u, curve_parameter):
         yield factor
      return

   g2 = gcd(curve_parameter**2 - 5, f)
   if g2 not in (1, f):
      for factor in sub_sub_sure_factors(g2, u, curve_parameter):
         yield factor
      for factor in sub_sub_sure_factors(f / g2, u, curve_parameter):
         yield factor
      return

   if f in (g, g2):
      yield f

   while still_a_chance:
      p1 = get_points([curve_parameter], f)
      for prime in primes:
         p1 = multiply(p1, prime, f)
         if not isinstance(p1, list):
            if p1 != f:
               for factor in sub_sub_sure_factors(p1, u, curve_parameter):
                  yield factor
               for factor in sub_sub_sure_factors(f/p1, u, curve_parameter):
                  yield factor
               return
            else:
               still_a_chance = False
               break

      if not still_a_chance:
         break

      prime = 1
      still_a_chance = False
      while prime < u2:
         prime = next_prime(prime)
         should_break = False
         for _ in xrange(int(log_mo / math.log(prime))):
            p1 = multiply(p1, prime, f)
            if not isinstance(p1, list):
               if p1 != f:
                  for factor in sub_sub_sure_factors(p1, u, curve_parameter):
                     yield factor
                  for factor in sub_sub_sure_factors(f/p1, u, curve_parameter):
                     yield factor
                  return

               else:
                  still_a_chance = True
                  primes.append(prime)
                  should_break = True
                  break
         if should_break:
            break

   for i in xrange(2, int(math.log(f) / LOG_2) + 2):
      r = root(f, i)
      if r[1]:
         for factor in sub_sub_sure_factors(r[0], u, curve_parameter):
            for _ in xrange(i):
               yield factor
         return

   a = 1 + sqrt(f)
   bsq = a * a - f
   iter = 0

   while bsq != sqrt(bsq)**2 and iter < 3:
      a += 1
      iter += 1
      bsq += a + a - 1

   if bsq == sqrt(bsq)**2:
      b = sqrt(bsq)
      for factor in sub_sub_sure_factors(a - b, u, curve_parameter):
         yield factor
      for factor in sub_sub_sure_factors(a + b, u, curve_parameter):
         yield factor
      return

   yield f
   return
Пример #60
0
import gmpy2

N = gmpy2.mpz(
    0xE8953849F11E932E9127AF35E1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000051F8EB7D0556E09FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBAD55
)
gmpy2.get_context().precision = 2048
a = int(gmpy2.sqrt(N))
a2 = a * a
b2 = gmpy2.sub(a2, N)
while not (gmpy2.is_square(b2)):
    a = a + 1
    b2 = a * a - N
b2 = gmpy2.mpz(b2)
gmpy2.get_context().precision = 2048
b = int(gmpy2.sqrt(b2))
p = a + b
q = a - b
print p
print q