def aks_test(n): """ Implement the AKS primality test. """ get_context().precision = bit_length(n) # Check if n is a perfect power. If so, return composite. if is_power(n): return "composite" # Find the smallest r such that the multiplicative order of n modulo r # is greater than log(n, 2)^2 r = get_r(n) # If 1 < gcd(a, n) < n for some a <= r, return composite for a in range(1, r): if gcd(a, n) > 1 and gcd(a, n) < n: return "composite" # If n <= r, return prime if n <= r: return "prime" # Check if (x + a)^n mod (x^r - 1, n) != (x^n + a) mod (x^r - 1, n) if False in ray.get([ is_congruent.remote(a, n, r) for a in range(1, mpz(floor(sqrt(phi(r)) * log2(n)))) ]): return "composite" return "prime"
def check(self, i): #区间大小 diff = self.right - self.left #新的左右区间 curleft = self.left + diff * self.lp1[i] curright = self.left + diff * self.rp1[i] #读取的数转化为小数 decimal = gmpy2.mpfr(self.cur / self.log10) decimal = decimal - gmpy2.floor(decimal) #判断是否满足要求 if curleft > decimal: return False if curright < decimal: return False #更新区间 self.left = curleft self.right = curright #通过decimal计算新的cur,抛弃掉cur前导多余数字,cur维持为整数防止精度缺失 self.cur = decimal*self.log10 self.cur = gmpy2.rint_round(self.cur) return True
def bits_in_number(number): """ Returns number of bits in the given number :param number: long number """ if number == 0: return 0 return gmpy2.mpz(gmpy2.floor(gmpy2.log2(number)) + 1)
def find_limits(): # create an empty dictionary limits = {} for planet in xrange(1, 10): # read date files, one per planet file_in = open('VSOP2013p' + str(planet) + '.dat') # create a list with the header position and values for variables planet, var, power elenco = [(s[0], s[1].split()) for s in enumerate(file_in) if "VSOP" in s[1]] file_in.close() # extend the dictionary with a subdictionary for each planet limits[planet] = {} for var in xrange(1, 7): # extend the dictionary with a subdictionary for each variable limits[planet][var] = {} for power in xrange(0, 21): # extend the dictionary with a subdictionary for each power limits[planet][var][power] = {} for threshold in xrange(0, 21): # extend the dictionary with a two values tuple (min and max) # for each sensibility threshold # and for each item in list assign (0,0) to the tuple limits[planet][var][power][threshold] = (0, 0) # create a tuple with range limits for each planet, variable, power for i in xrange(len(elenco)): start = int(elenco[i][0]) + 1 planet = int(elenco[i][1][1]) var = int(elenco[i][1][2]) power = int(elenco[i][1][3]) end = int(elenco[i][1][4]) + start # load a file chunk for each voice in list and find extreme value for each threshold file_in = open('VSOP2013p' + str(planet) + '.dat') segmento = islice(file_in, start, end) for j, k in enumerate(segmento): cursor = j line = k.split() Sb = float(line[-4]) Se = int(line[-3]) S = Sb * 10**Se Cb = float(line[-2]) Ce = int(line[-1]) C = Cb * 10**Ce ro = gmp.sqrt(S * S + C * C) threshold = -int(gmp.floor(gmp.log10(ro))) limits[planet][var][power][threshold] = (start, start + cursor) file_in.close() for planet in xrange(1, 10): for var in xrange(1, 7): for power in xrange(0, 21): for threshold in xrange(1, 21): prec_ = limits[planet][var][power][threshold - 1] subs_ = limits[planet][var][power][threshold] if subs_ == (0, 0) and prec_ != 0: limits[planet][var][power][threshold] = limits[planet][ var][power][threshold - 1] return limits
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'
def format(num): s = '' si = '' if num < GSConst.c[0]: num = -num si = '-' num1 = mpz(floor(num)) while 1: s = str(num1 % 10) + s num1 -= num1 % 10 num1 /= 10 if num1 <= 0: break s += '.' num1 = num - floor(num) for i in range(100): num1 *= 10 s += str(mpz(floor(num1))) num1 -= floor(num1) s = si + s return s
def ex3(): N = mpz( 720062263747350425279564435525583738338084451473999841826653057981916355690188337790423408664187663938485175264994017897083524079135686877441155132015188279331812309091996246361896836573643119174094961348524639707885238799396839230364676670221627018353299443241192173812729276147530748597302192751375739387929 ) sqrt_6N = sqrt(6 * N) sqrt_6N_decimal = sqrt_6N % 1 if sqrt_6N_decimal < 0.5: A = floor(sqrt_6N) + 0.5 else: A = ceil(sqrt_6N) x = sqrt(A**2 - 6 * N) # P = 3 * p # Q = 2 * q P = A - x p = mpz(P / 3) print(p)
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
def lsb_oracle(public_key, ciphertext, oracle): # type: (RSAKey, RSACiphertext, Callable[[RSACiphertext], bool]) -> RSAPlaintext r""" The Least Significant Bit Oracle attack is a simpler variation on Bleichenbacher. It assumes a decryption oracle :math:`LSB(\dot)` that accepts ciphertexts and returns the least significant or parity bit of the decrypted plaintext. """ mult = powmod(2, public_key.e, public_key.n) t = (ciphertext * mult) % public_key.n lower = mpfr(0) upper = mpfr(public_key.n) for i in range(public_key.n.bit_length()): possible_plaintext = (lower + upper) / 2 if not oracle(int(t)): upper = possible_plaintext # plaintext is in the lower half else: lower = possible_plaintext # plaintext is in the upper half t = (t * mult) % public_key.n return mpz(floor(upper))
err=0 try: p=remote('programming.pwn2win.party','9004',ssl=1) except: err=err+1 if err>10 : break continue s='' t=0 while 1: s='' s=p.recv() if s.startswith('CTF-BR{') or s == 'WRONG ANSWER': break if 'WRONG' in s: break n1= gmpy2.mpz(s) n=gmpy2.floor((gmpy2.sqrt(n1)-1)/2) print 'n='+str(n) n2=(2*n+1)*(2*n+1) d=n1-n2 print 'd='+str(d) v1=2*n+1 v2=2*n+1+2*(n+1) v3=2*n+1+4*(n+1) v4=2*n+1+4*(n+1)+2*(n+1)+1 x=0 y=0 if d<v1: x=n+1 y=d-n elif d<v2: x=n+1-(d-v1)
from gmpy2 import mpz, isqrt, floor data = open('a.txt', 'r').read().split('\n') T = int(data.pop(0)) for t in range(T): (r, ml) = map(mpz, data.pop(0).split(' ')) a = mpz('2') b = mpz(2 * r - 1) c = mpz(-1 * ml) ans = int(floor((isqrt(mpz(b * b - 4.0 * a * c)) - b) / (2.0 * a))) print 'Case #' + str(t + 1) + ": " + str(ans)
def getexponent(self): return int(gmpy2.floor(self.log().val))
err = 0 try: p = remote('programming.pwn2win.party', '9004', ssl=1) except: err = err + 1 if err > 10: break continue s = '' t = 0 while 1: s = '' s = p.recv() if s.startswith('CTF-BR{') or s == 'WRONG ANSWER': break if 'WRONG' in s: break n1 = gmpy2.mpz(s) n = gmpy2.floor((gmpy2.sqrt(n1) - 1) / 2) print 'n=' + str(n) n2 = (2 * n + 1) * (2 * n + 1) d = n1 - n2 print 'd=' + str(d) v1 = 2 * n + 1 v2 = 2 * n + 1 + 2 * (n + 1) v3 = 2 * n + 1 + 4 * (n + 1) v4 = 2 * n + 1 + 4 * (n + 1) + 2 * (n + 1) + 1 x = 0 y = 0 if d < v1: x = n + 1 y = d - n elif d < v2: x = n + 1 - (d - v1)
def is_prime_by_AKS(n): """ 使用AKS算法确定n是否是一个素数 True:n是素数 False:n是合数 """ def __is_integer__(n): """ 判断一个数是否是整数 """ i = gmpy2.mpz(n) f = n - i return not f def __phi__(n): """ 欧拉函数,测试小于n并与n互素的个数 """ res = gmpy2.mpz(n) a = gmpy2.mpz(n) for i in range(2, a + 1): if a % i == 0: res = res // i * (i - 1) while a % i == 0: a //= i if a > 1: res = res // a * (a - 1) return res def __gcd__(a, b): """ 计算a b的最大公约数 """ if b == 0: return a return __gcd__(gmpy2.mpz(b), gmpy2.mpz(a) % gmpy2.mpz(b)) print("步骤1, 确定%d是否是纯次幂" % n) for b in range(2, gmpy2.mpz(gmpy2.floor(gmpy2.log2(n))) + 1): a = n**(1 / b) if __is_integer__(a): return False print("步骤2,找到一个最小的r,符合o_r(%d) > (log%d)^2" % (n, n)) maxk = gmpy2.mpz(gmpy2.floor(gmpy2.log2(n)**2)) maxr = max(3, gmpy2.mpz(gmpy2.ceil(gmpy2.log2(n)**5))) nextR = True r = 0 for r in range(2, maxr): if nextR == False: break nextR = False for k in range(1, maxk + 1): if nextR == True: break nextR = (gmpy2.mpz(n**k % r) == 0) or (gmpy2.mpz(n**k % r) == 1) r = r - 1 # 循环多增加了一层 print("r = %d" % r) print("步骤3,如果 1 < gcd(a, %d) < %d,对于一些 a <= %d, 输出合数" % (n, n, r)) for a in range(r, 1, -1): g = __gcd__(a, n) if g > 1 and g < n: return False print("步骤4,如果n=%d <= r=%d,输出素数" % (n, r)) if n <= r: return True print("步骤5") print("遍历a从1到\sqrt{\phi(r=%d)}logn=%d" % (r, n)) print("如果(X+a)^%d != X^%d+a mod {X^%d-1, %d}$输出合数" % (n, n, r, n)) # 构造P = (X+a)^n mod (X^r-1) print("构造多项式(X+a)^%d,并且进行二项式展开" % n) X = multi_ysymbols('X') a = multi_ysymbols('a') X_a_n_expand = binomial_expand(ypolynomial1(X, a), n) print(X_a_n_expand) X.pow(r) reduce_poly = ypolynomial1(X, ysymbol(value=-1.0)) print("构造消减多项式 %s" % reduce_poly) print("进行运算 (X+a)^%d mod (X^%d-1)" % (n, r)) r_equ = ypolynomial_mod(X_a_n_expand, reduce_poly) print("得到余式: %s" % r_equ) print("进行运算'余式' mod %d 得到式(A)" % n) A = ypolynomial_reduce(r_equ, n) print("A = %s" % A) print("B = x^%d+a mod x^%d-1" % (n, r)) B = ypolynomial1(multi_ysymbols('X', power=31), a) B = ypolynomial_mod(B, reduce_poly) print("B = %s" % B) C = ypolynomial_sub(A, B) print("C = A - B = %s" % C) maxa = math.floor(math.sqrt(__phi__(r)) * math.log2(n)) print("遍历a = 1 to %d" % maxa) print("检查每个'%s = 0 (mod %d)'" % (C, n)) for a in range(1, maxa + 1): print("检查a = %d" % a) C.set_variables_value(a=a) v = C.eval() if v % n != 0: return False print("步骤6 输出素数") return True
#!/usr/bin/env python3 # Calculates floor(2**256/pi), and encodes the result as base64. # Intended to be used as a SHA256 hash where I don't have a preimage up my sleeve. # Originally by Ryan Castellucci. Python3 port, pi sourcing, and base64 output added by Jeremy Rand. import codecs, gmpy2 # precision in bits gmpy2.get_context().precision = 1024 # 1000 digits of pi from https://www.angio.net/pi/digits/1000.txt (first HTTPS result in Startpage results for "digits of pi") # (retrieved 2017 May 13.) pi_str = '3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475648233786783165271201909145648566923460348610454326648213393607260249141273724587006606315588174881520920962829254091715364367892590360011330530548820466521384146951941511609433057270365759591953092186117381932611793105118548074462379962749567351885752724891227938183011949129833673362440656643086021394946395224737190702179860943702770539217176293176752384674818467669405132000568127145263560827785771342757789609173637178721468440901224953430146549585371050792279689258923542019956112129021960864034418159813629774771309960518707211349999998372978049951059731732816096318595024459455346908302642522308253344685035261931188171010003137838752886587533208381420617177669147303598253490428755468731159562863882353787593751957781857780532171226806613001927876611195909216420198' pi_mpfr = gmpy2.mpfr(pi_str) fraction = gmpy2.floor(2**256 / pi_mpfr) hx = hex(int(fraction))[2:66] #print(hx) b64 = codecs.encode(codecs.decode(hx, "hex"), "base64").decode() print(b64)
#!/usr/bin/env python2 import sys, os import math import gmpy2 # Cases t = int(sys.stdin.readline()) gmpy2.get_context().precision=150 for case in xrange(t): r, t = map(int, sys.stdin.readline().rstrip('\n').split()) delta = (2*r-1)**2 + 8*t result = 0 if delta < 0: result = 0 else: result = int(gmpy2.floor((-(2*r-1)+gmpy2.sqrt(delta))/4)) print "Case #%d: %d" % (case+1, result)