def set_precision(number): """ Set the global gmpy2 precision. Set the global precision for all gmpy2 computations and numbers in current context. The gmpy2 precision is a bit width of stored numbers and it is approximately 3 to 5 bits per digits (take 5 bits per digits into account). Parameters ---------- number : int or str Global gmpy2 precision in number of displayed digits. Raises ------ error.PrecisionError If `precision` has not acceptable format for precision. """ try: gmpy2.get_context().precision = 5 * int(number) debug("gmpy2 precision: {} bits".format(gmpy2.get_context().precision)) except: raise error.PrecisionError
def N(value, prec=6): pre_prec = gmp.get_context().precision adj_prec = int((prec * (gmp.log(2) + gmp.log(5))) / gmp.log(2)) gmp.get_context().precision = adj_prec try: x, y = getattr(value, 'numerator'), getattr(value, 'denominator') return x / y except AttributeError: return value
def compute(self): gmpy2.get_context().precision = self.precision x = mpfr(self.threshold) ceilx = gmpy2.next_above(x) gmpy2.get_context().precision = 53 ceilx = (x + ceilx) / 2 X = UniformDistr(self.lowerbound, self.upperbound) self.error_prob = (X.get_piecewise_pdf().integrate( x, ceilx)) / (X.get_piecewise_pdf().integrate(x, self.upperbound))
def compute(self): gmpy2.get_context().precision = self.precision x = mpfr(self.threshold) ceilx = gmpy2.next_above(x) floorx = gmpy2.next_below(x) gmpy2.get_context().precision = 53 ceilx = (x + ceilx) / 2 floorx = (floorx + x) / 2 X = UniformDistr(self.lowerbound1, self.upperbound1) Y = UniformDistr(self.lowerbound2, self.upperbound2) Z = X + Y self.error_prob = (((ceilx - x) / (ceilx - floorx)) * Z.get_piecewise_pdf().integrate(x, ceilx))
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)}
def test1(self,n,p,prec,matrix_type,method): ''' check the quality of tridiagonalization. ''' if p==2: assert(method=='qr' or method=='sqrtm') else: assert(method=='qr') if prec is not None: gmpy2.get_context().precision=prec assert(matrix_type in ['array','sparse','mpc']) v0=self.gen_randv0(n,p,matrix_type='array') H0=self.gen_randomH(n,p,matrix_type=matrix_type) if p is not None: if method=='qr': data,offset=tridiagonalize_qr(H0,q=v0,prec=prec) else: data,offset=tridiagonalize2(H0,q=v0,prec=prec) else: data,offset=tridiagonalize(H0,q=v0,prec=prec) B=construct_tridmat(data,offset).toarray() if sps.issparse(H0): H0=H0.toarray() H0=complex128(H0) e1=eigvalsh(H0) e2=eigvalsh(B) assert_allclose(e1,e2)
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) }
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
def modulus_inutilis(): n = 17258212916191948536348548470938004244269544560039009244721959293554822498047075403658429865201816363311805874117705688359853941515579440852166618074161313773416434156467811969628473425365608002907061241714688204565170146117869742910273064909154666642642308154422770994836108669814632309362483307560217924183202838588431342622551598499747369771295105890359290073146330677383341121242366368309126850094371525078749496850520075015636716490087482193603562501577348571256210991732071282478547626856068209192987351212490642903450263288650415552403935705444809043563866466823492258216747445926536608548665086042098252335883 e = 3 ct = 243251053617903760309941844835411292373350655973075480264001352919865180151222189820473358411037759381328642957324889519192337152355302808400638052620580409813222660643570085177957 gmpy2.get_context().precision = 1000 plaintext = int(gmpy2.cbrt(ct)) return trans(plaintext)
def get_snapped_noise(self): """ Generates noise for Snapping Mechanism See section 5.2 of Mironov (2012) for the definition of the snapping mechanism implemented below. """ gmpy2.get_context().precision = self.precision # scale mechanism input by sensitivity mechanism_input_scaled = self.mechanism_input / self.sensitivity # generate random sign and draw from Unif(0,1) sign = gmpy2.mpfr( 2 * secrets.randbits(1) - 1 ) # using mpfr precision here, even though it's an integer, so that the # precision carries through in later steps u_star_sample = self._sample_from_uniform() inner_result = self._clamp(mechanism_input_scaled, self._B_scaled) + ( sign * 1 / self.epsilon_prime * crlibm.log_rn(u_star_sample)) # perform rounding/snapping inner_result_rounded = self._get_closest_multiple_of_Lambda( inner_result, self._m) private_estimate = self._clamp( self.sensitivity * inner_result_rounded, self.B) # put private estimate back on original scale snapped_noise = private_estimate - self.mechanism_input return (snapped_noise)
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 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)
def _ptwise_vals_equal(mp_val, np_val, epsilon): """Pointwise value comparison""" ptwise_diff = abs(mp_val - mpfr(np_val)) if epsilon == None: P = gmpy2.get_context().precision epsilon = mpfr("0b" + "0" * P + "1") return ptwise_diff < epsilon
def legendre_symbol(): p = 101524035174539890485408575671085261788758965189060164484385690801466167356667036677932998889725476582421738788500738738503134356158197247473850273565349249573867251280253564698939768700489401960767007716413932851838937641880157263936985954881657889497583485535527613578457628399173971810541670838543309159139 ints = [ 25081841204695904475894082974192007718642931811040324543182130088804239047149283334700530600468528298920930150221871666297194395061462592781551275161695411167049544771049769000895119729307495913024360169904315078028798025169985966732789207320203861858234048872508633514498384390497048416012928086480326832803, 45471765180330439060504647480621449634904192839383897212809808339619841633826534856109999027962620381874878086991125854247108359699799913776917227058286090426484548349388138935504299609200377899052716663351188664096302672712078508601311725863678223874157861163196340391008634419348573975841578359355931590555, 17364140182001694956465593533200623738590196990236340894554145562517924989208719245429557645254953527658049246737589538280332010533027062477684237933221198639948938784244510469138826808187365678322547992099715229218615475923754896960363138890331502811292427146595752813297603265829581292183917027983351121325, 14388109104985808487337749876058284426747816961971581447380608277949200244660381570568531129775053684256071819837294436069133592772543582735985855506250660938574234958754211349215293281645205354069970790155237033436065434572020652955666855773232074749487007626050323967496732359278657193580493324467258802863, 4379499308310772821004090447650785095356643590411706358119239166662089428685562719233435615196994728767593223519226235062647670077854687031681041462632566890129595506430188602238753450337691441293042716909901692570971955078924699306873191983953501093343423248482960643055943413031768521782634679536276233318, 85256449776780591202928235662805033201684571648990042997557084658000067050672130152734911919581661523957075992761662315262685030115255938352540032297113615687815976039390537716707854569980516690246592112936796917504034711418465442893323439490171095447109457355598873230115172636184525449905022174536414781771, 50576597458517451578431293746926099486388286246142012476814190030935689430726042810458344828563913001012415702876199708216875020997112089693759638454900092580746638631062117961876611545851157613835724635005253792316142379239047654392970415343694657580353333217547079551304961116837545648785312490665576832987, 96868738830341112368094632337476840272563704408573054404213766500407517251810212494515862176356916912627172280446141202661640191237336568731069327906100896178776245311689857997012187599140875912026589672629935267844696976980890380730867520071059572350667913710344648377601017758188404474812654737363275994871, 4881261656846638800623549662943393234361061827128610120046315649707078244180313661063004390750821317096754282796876479695558644108492317407662131441224257537276274962372021273583478509416358764706098471849536036184924640593888902859441388472856822541452041181244337124767666161645827145408781917658423571721, 18237936726367556664171427575475596460727369368246286138804284742124256700367133250078608537129877968287885457417957868580553371999414227484737603688992620953200143688061024092623556471053006464123205133894607923801371986027458274343737860395496260538663183193877539815179246700525865152165600985105257601565 ] x = -1 for i in ints: if euler_criterion( i, p) == 1: # 1 means that the number is a quadratic residue x = i # this is the quadratic residue # a^2 = x mod p # b^p cong b mod p gmpy2.get_context().precision = 10000 # temp = gmpy2.div(p+1, 4) # print(temp) a = pow(x, int(gmpy2.div(p + 1, 4)), p) # a = (pow(x, p/2, p)) # print(int(a) == a) print(a)
def verif_quadra(phi, N): # coefficients are initialized a = 1 b = phi - N - 1 c = N #calculation of the determinant delta = b * b - 4 * a * c if delta < 0: return False #processing the roots n = gmpy2.mpz(delta) gmpy2.get_context().precision = 2048 det = gmpy2.sqrt(n) num1 = (-b + det) num2 = (-b - det) den = 2 * a k1 = int(num1 // den) r1 = num1 - k1 * den k2 = int(num2 // den) r2 = num2 - k2 * den if r1 == 0.0 and r2 == 0.0: return True else: return False
def worker(number, data, ppc): gmpy2.get_context().precision = 100 m = 1 setup(ppc) temp_data = [[0 for i in range(N)] for i in range(N)] mm = [[gmpy2.mpfr(0.0) for i in range(N)] for ii in range(N)] ss = [[0 for i in range(N)] for ii in range(N)] v0 = 0.0 #v([]) vector = list(range(N)) while (True): for i in range(0, m, N): shuffle(vector) prev_v = v0 spruik_solver() for ii, vv in enumerate(vector): #size ii, player vv new_v = v(vector[0:ii + 1]) x = new_v - prev_v prev_v = new_v mm[ii][vv] += x mm[N - ii - 1][vv] += x ss[ii][vv] += 1 ss[N - ii - 1][vv] += 1 for i in range(N): for ii in range(N): temp_data[i][ii] = mm[i][ii] / ss[i][ii] if ss[i][ ii] > 0 else 0 #indsplus*random()*2.0/N #random()*1000 data[number] = [ float(sum([temp_data[o][i] for o in range(N)]) / N) for i in range(N) ]
def _read_sighash_config(self, sig_cfgf): # get pool/poolkey config from given .mbrat file self.cfgparser.read(path.abspath(sig_cfgf)) print path.abspath(sig_cfgf) # set precision try try: prec = self.cfgparser.getint('poolkey', 'prec') except ConfigParser.NoOptionError: return None gmpy2.get_context().precision = prec # check to see if the poolkey already exists, else create it # sig_pool = sig_d = {} for sec in self.cfgparser.sections(): if sec == 'poolkey': sig_d[sec] = { 'name': self.cfgparser.get(sec, 'name'), 'prec': prec, 'iters': self.cfgparser.getint(sec, 'iters'), 'mpoint': mpc( self.cfgparser.get(sec, 'mpoint') ), } elif sec == 'signature': hash_sig_s = self.cfgparser.get(sec, 'hash_sig') sig_d[sec] = { 'hash_sig': [mpc(pt) for pt in hash_sig_s.split('\n')] } return sig_d
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
def Run_MFun(self, itermax, Z_0): """ Expects gmpy2.mpc type for Z_0. """ if not gmpy2.get_context().precision == self.prec: gmpy2.get_context().precision = self.prec Z = Z_0 while self.iters < itermax: Z = add( gmpy2.mul(Z,Z), self.C ) if norm(Z) > 4.0: break self.iters += 1 if self.iters == itermax: self.inmset = True
def create(self, string, round=0): ctx = gmpy2.ieee(self.format) ctx.round = MPFR_Data.rounding[round] gmpy2.set_context(ctx) fpo = gmpy2.mpfr(string) ctx = gmpy2.get_context() # Get the results self.ctx = ctx.copy() # Copy the context for later status return fpo
def precision_hook(self, value): fp_format = {'single': 32, 'double': 64}.get(value, None) if fp_format is not None: value = gmpy2.ieee(fp_format).precision - 1 if isinstance(value, str): value = int(value) gmpy2.get_context().precision = value + 1 return value
def testSquare(num): gmpy2.get_context().precision = 100000 sqrt = int(gmpy2.sqrt(num)) # print("Square: " + str(sqrt)) for i in range(sqrt, 1, -1): if (num % i) == 0: print("Result: " + str(i) + " q: " + str(num // i)) return i, num // i
def main(): from sys import argv if len(argv) > 1: gmpy2.get_context().precision = 5000 if argv[1] == '--sign': sign() if argv[1] == '--check': check()
def create(self,string,round=0): ctx=gmpy2.ieee(self.format) ctx.round=MPFR_Data.rounding[round] gmpy2.set_context(ctx) fpo=gmpy2.mpfr(string) ctx=gmpy2.get_context() # Get the results self.ctx=ctx.copy() # Copy the context for later status return fpo
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
def set_context_precision(mantissa, exponent): ctx = gmpy2.get_context() #precision is already +1, meaning in single precision is 24 (and not 23) ctx.precision = mantissa ctx.emax = 2**(exponent - 1) # 4-emax-precision #https://github.com/aleaxit/gmpy/issues/103 ctx.emin = 4 - ctx.emax - ctx.precision return ctx
def avg_error(coeffs, trials, max): gmpy2.get_context().precision = 256 total_error = 0 for i in range(trials): x = random.random()*max expected = gmpy2.log(x) * 2**64 result = fxp_ln(int(x*2**64), coeffs) total_error += abs(result - expected)/expected return total_error/trials
def fib_eig(k): import gmpy2 ctx = gmpy2.get_context() ctx.precision += 1000 sqrt5 = gmpy2.sqrt(5) lambda1 = (1 + sqrt5) / 2 lambda2 = (1 - sqrt5) / 2 fk = (lambda1**k - lambda2**k) / (lambda1 - lambda2) return int(fk)
def calc(): # gmpy2.get_context().precision = 3321925 start = time.time() for i in range(3321925, 3321930): t = time.time() gmpy2.get_context().precision = i res = str(gmpy2.sqrt(2)) print("精度设置为{}, 运算长度为{}, 第一百万位数字是{}, 本次用时{}".format(i, len(res), res[-1], time.time() - t)) end = time.time() print("总用时{}秒".format(end - start))
def main(): gmpy2.set_context(gmpy2.context()) gmpy2.get_context().precision = 75 T = int(input()) if T < 1 or T > 100: raise RuntimeError("T is not within the valid range") for i in range(T): n = int(input()) r = Numbers(n) print("Case #" + str(i + 1) + ": " + r)
def __init__(self): #set the precision for gmpy to very high gmpy2.get_context().precision=5000 self.N = 0 self.p = 0 self.q = 0 self.e = 0 self.d = 0 self.pi_of_N = 0 self.pkcsByte = "02" self.separatorByte = "00"
def recover_msg(N1, N2, N3, C1, C2, C3): m = 42 # your code starts here: to calculate the original message - m # Note 'm' should be an integer N = N1 * N2 * N3 #y1 = N / N1 #y2 = N / N2 #y3 = N / N3 s = [1, 0] r = [(N / N1), N1] i = 2 temp = (N / N1) % N1 while (temp > 0): temp = r[i - 2] % r[i - 1] r.append(temp) s.append(s[i - 2] - (r[i - 2] / r[i - 1]) * s[i - 1]) i += 1 z1 = s[i - 2] s = [1, 0] r = [(N / N2), N2] i = 2 temp = (N / N2) % N2 while (temp > 0): temp = r[i - 2] % r[i - 1] r.append(temp) s.append(s[i - 2] - (r[i - 2] / r[i - 1]) * s[i - 1]) i += 1 z2 = s[i - 2] s = [1, 0] r = [(N / N3), N3] i = 2 temp = (N / N3) % N3 while (temp > 0): temp = r[i - 2] % r[i - 1] r.append(r[i - 2] % r[i - 1]) s.append(s[i - 2] - (r[i - 2] / r[i - 1]) * s[i - 1]) i += 1 z3 = s[i - 2] if z1 < 0: z1 += N1 if z2 < 0: z2 += N2 if z3 < 0: z3 += N3 x = (z1 * C1 * (N / N1) + z2 * C2 * (N / N2) + z3 * C3 * (N / N3)) % N gmpy2.set_context(gmpy2.context()) gmpy2.get_context().precision = 1000000 m = int(gmpy2.cbrt(x)) # your code ends here # convert the int to message string msg = hex(m).rstrip('L')[2:].decode('hex') return msg
def machin_gmpy2(digits): # Precision + 20 bits for safety gmpy2.get_context().precision = int(math.log2(10) * digits) + 20 one_5th = mpfr("1") / 5 one_239th = mpfr("1") / 239 pi_fourths = 4*gmpy2.atan(one_5th) - gmpy2.atan(one_239th) pi = 4*pi_fourths return pi
def __init__(self): # Set number of bits to keep around gmpy2.get_context().precision = 2000 # These are values taken from the OEIS which I use when # checking my results. self.lambdainf = mpfr( "3.5699456718709449018420051513864989367638369115148323781079755299213628875001367775263210342163" ) self.delta = mpfr( "4.669201609102990671853203820466201617258185577475768632745651343004134330211314" )
def get_prec(): prec = 3000000 while True: gmpy2.get_context().precision = prec res = str(gmpy2.sqrt(2)) print(prec, len(res)) if len(res) >= 1000002: print(res[-1], len(res), prec) break else: prec += 1 return prec
def main(): gmpy2.get_context().precision = 100 for dir_entry in os.scandir(): try: run_record = read_pcreo_file(dir_entry) print("Successfully read PCreo output file:", dir_entry.name) except: print("File", dir_entry.name, "is not a PCreo output file.") sys.exit(0) continue print(len(defect_classes(run_record))) povray_draw(run_record, 800, dir_entry.name)
def find_nearest_power(number): gmpy2.get_context().precision = 10000 smallest_r = number nearest_xy = 0 for i in range(2, int(math.log(number, 2))): floor = int(gmpy2.root(mpfr(number), i))**i if number - floor < smallest_r: if floor > number: print("error at %d" % i) smallest_r = number - floor nearest_xy = floor return smallest_r
def check_context(self): """ Check that the context settings including precision and inexact arithmetic flags are set properly. """ if self.precision_set != True: return False ctx = gmpy2.get_context() if ctx.precision != self.context.precision: return False else: return (ctx.trap_inexact and ctx.trap_overflow and ctx.trap_erange \ and ctx.trap_divzero and ctx.trap_invalid and ctx.trap_expbound \ and ctx.trap_underflow)
def run_sign(self, args, return_dict=False): """ Method to sign a hash of a given file, returning either True or a dict if return_dict==True. """ from mbrat.spi.sign import SignSPI spi = SignSPI(mandelfun) print "Signing '{0}' with profile '{1}:{2}' and pool '{3}:{4}' ...".format( args.file, self.config.get('name'), self.privkey_cfg.get('name'), self.pool_cfg.get('name'), self.poolkey_cfg.get('name') ) # put together arguments for the SPI args.spi['iters'] = int(self.pool_cfg.get('iters')) + \ int(self.privkey_cfg.get_from_section('pool', 'iters')) # set the precision args.spi['prec'] = int(self.privkey_cfg.get('prec')) gmpy2.get_context().precision = args.spi['prec'] # format the keys for mpc args.spi['poolkey'] = mpc( self.poolkey_cfg.get('real') + " " \ + self.poolkey_cfg.get('imag') ) args.spi['privkey'] = mpc( self.privkey_cfg.get('real') + " " \ + self.privkey_cfg.get('imag') ) ######## sign the hash ######## hash_sig = spi.run(args) # init a ConfigParser compat dict with a top-section of 'mhash' sig_d = {'mhash': {'prec': args.spi['prec']}} for sec in ['pool', 'poolkey']: sig_d[sec] = self.cfgmgr.secmgr[sec].get_as_args( subsection=sec, return_dict=True) sig_d['signature'] = { 'hash_sig': hash_sig } # add hash_sig # return a dict if desired ... if return_dict: return sig_d # ... or get the filename for the signature 'BASENAME.mbrat' file sig_cfgf = path.splitext(path.basename(args.file))[0] + ".mbrat" sig_cfgf = path.join( path.dirname(path.abspath(args.file)), sig_cfgf ) self._write_sig_config(sig_d, sig_cfgf) return True
def solve_second(N): gmpy2.get_context().precision = 1000 Nsqrt = gmpy2.isqrt(N) for A in range(Nsqrt , Nsqrt+2**20): A2 = A*A diff = A2 - N if diff > 0: possible_x = gmpy2.isqrt(A2 - N) if (A-possible_x) * (A+possible_x) == N: print "#2 ----> P is: " + str(A-possible_x) break else: print "Error: P not found!"
def test_roundings(self): gmpy2.get_context().real_round = gmpy2.RoundToNearest for test_vector in scalar_decomp_test_vectors: scalar = test_vector[0] # alpha_tilde = floor(ell_i * m / mu) ~ round((alpha_hat_i / N) * scalar) alpha_tildes = scalar_decomposition.calculate_alpha_tildes(scalar) alpha_hats = scalar_decomposition.calculate_alpha_hats() # the values of alpha_tilde should be equal to round((alpha_hat / N) * m) for alpha_tilde, alpha_hat in zip(alpha_tildes, alpha_hats): alpha_rounded = round(mpq(alpha_hat * scalar, constants.N)) # computing the rounding in this way means the answer can be out by 1 in some cases diff = alpha_rounded - alpha_tilde self.assertTrue(0 <= diff <= 1)
def fermat_factorization(n): factor_list = [] gmpy2.get_context().precision = 2048 a = int(gmpy2.sqrt(n)) a2 = a * a b2 = gmpy2.sub(a2, n) while True: a += 1 b2 = a * a - n if gmpy2.is_square(b2): b2 = gmpy2.mpz(b2) gmpy2.get_context().precision = 2048 b = int(gmpy2.sqrt(b2)) factor_list.append([a + b, a - b]) if len(factor_list) == 2: break return factor_list
def main(): gmpy2.get_context().precision = 10000 p = 0x16498bf7cc48a7465416e0f9ec8034f4030991e73aff9524ef74cc574228e36e6e1944c7686f69f0d1186a69b7aa77d7e954edc8a6932f006786f4648ecc8d4f4d3f6c03d9a1ee9fe61b28b6dd2791a63be581b8811a8ac90a387241ea68b7d36b4a274f64c7a721ad55cfcef23cd14c72542f576e4b507c11c4fa198e80021d484691b e = 0x69420 ct1 = 0xa82b37d57b6476fa98f6ee7c278d934bd96c49aa1c5399552d25211230d76cb16ade049572bf631e3849903638d41c884957b9592d0aa072b2bdc3105fe0e3253284f85286ec613966f9cde77ae06e2053dc2254e44ca673b4c76879eff84e5fc32af976c1bfafe147a277d72aad674db749ed8f34d2ebe8189cf12afc9baa17764e4b phi = p - 1 const = 32 e //= const d = gmpy2.invert(e, phi) # print(d) p32 = pow(ct1, d, p) # print(p32) while (const != 1): const //= 2 p32 = tonelli_shanks(p32, p) # print(trans(-p32%p)) # FIRST PART OF THE FLAG BABY: HTB{why_d1d_y0u_m3ss_3v3ryth1ng_up_1ts_n0t_th4t_h4rd p = 0x16498bf7cc48a7465416e0f9ec8034f4030991e73aff9524ef74cc574228e36e6e1944c7686f69f0d1186a69b7aa77d7e954edc8a6932f006786f4648ecc8d4f4d3f6c03d9a1ee9fe61b28b6dd2791a63be581b8811a8ac90a387241ea68b7d36b4a274f64c7a721ad55cfcef23cd14c72542f576e4b507c11c4fa198e80021d484691b n = 0xbe30ccaf896c16f53515e298df25df9158d0a95295c119f0444398b94fae26c0b4cf3a43b120cf0fb657069e0621eb1d2dd832eef3065e80ddbc35854dd4585cc41fd6a5b36339c0d9fcc066272be6818be6a624f75482bbb9c408010ac8c27b20397d870bfcb14e6318097b1601f99e391c9b68c5c586f8da561ff8507be9212713b910b748370ce692c11afa09b74ce80c5f5dd72046415aeed85e1ecedca14abe17ed19ab97729b859120699d9f80dd13f8483773df15b938b8399702a6e846b8728a70f1940d4c6e5835a06a89925eb1ec91a796f270e2d9be1a2c4bee5517109c161f04333d9c0d4034fbbd2dcf69fe734b759a89937f4d8ea0ee6b8385aae14a2cce361 # generator g = 0x69420 ct2 = 0x65d57a564b8a8667a956705442063392b9b975b8ef869a6dbed04d6e585351f559fe6f5d96823f60b7306740fe2cf5aa81e4a12736d4f0a4826cbc8b4312643af19c75432b4ab222837031851f312df5d707b39bdf2d272f25c1947f3e2943f3592cb0519fee8f4b458021b6b8ee4eabeeae5127d412df4f6a88f66d7cc34c6bb77e0a1440737d0e167f9489f0c7fbfd7f6a5870b4b2865d29b91f6c2b375951e85b1b9f03887d4d3c4a6218111a95021ed1d554c57269e7830c3e7b8e17d13e1fb75ee9f305833d0cb6bfab738572cdbbc8b33b878ad25f78d47d7f449a6c348f5f9f1df3e09f924534a3669b4e69bd0411d154ec756b210691e2efc4a55aa664d938a868f4d # print(n) # print(g) # print(ct2) q = n // p # print(q) # found using alpertron for g^xp = ct2 mod p kp = 0 xp = 1333647771826129906056278980508785116695001357398405010264712880010822066437928270470093887443647579332557329757513503832688236838814545646539928049413880950956136391197700699813257009513030650710096103937450573603079886862042789301653172344151731360918260335579808862271014412080624561537897979314727207446470188301\ + 2100597191236862411973123184673222390029361412634375676811383630091967723602897705208854139513327705418840522104410271985778087477636285771639551773018473451844243204190875248518748762236574766561778114516538828518726261981381313004189199195300204873125911752732961129454366019842676645748294495098918135199007126669 * kp kq = 0 xq = 2248237925279582319646346402167252499424555860028602832387207824347301477610684362756745372458799004275280799304910420404269790625413034441525997676464275232206297649095612480172888211521015846455387388707653809767187874172857528680924943045273311447383766726890650161662310150531795567852223701545458237821806704227\ + 25737553036453033170874873232492616472696251153498345345893349066914349319700028526259065151440470760781885101651616163782998343068021108194360596481454344775056268387636520767391616783538213196153998980567585557740463660083917063025907541863194906635695830144597030344814258845557193440907517374289359866191267367218 * kq assert (pow(g, xp, p) == ct2 % p) assert (pow(g, xq, q) == ct2 % q) m = [p - 1, q - 1] # modulo v = [xp, xq] ret = crt(m, v) print(ret[0]) # gives x in g^x # # check assert (xp == ret[0] % (p - 1)) assert (xq == ret[0] % (q - 1)) print(trans(ret[0]))
def getFinalMaxValue(self, supVal): if not gmpy2.is_finite(supVal): print("Error cannot compute intervals with infinity") exit(-1) bkpCtx = gmpy2.get_context().copy() i = 0 while not gmpy2.is_finite(gmpy2.next_above(supVal)): set_context_precision(self.precision + i, self.exponent + i) i = i + 1 prec = printMPFRExactly(gmpy2.next_above(supVal)) gmpy2.set_context(bkpCtx) return prec
def _assert_mp_equals_np(mp_array, np_array): """Compares an MPMatrix and np array, checking for equality. Returns an equality bool and an error string.""" m, n = np_array.shape coordinates = itertools.product(range(m), range(n)) P = gmpy2.get_context().precision # TODO: need this to be relative epsilon = mpfr("0b" + "0" * P + "1") for coord in coordinates: mp_val = mp_array[coord] np_val = np_array[coord] if not _ptwise_vals_equal(mp_val, np_val, epsilon): return (False, "Distinct values mp: {}, np: {} at coord {}".format( mp_val, np_val, coord)) return (True, "")
def main(): # Configure precision to deal with large integers # The right factor(3) must be found by trial and error; turns out that to solve these # problems a precision of around 900 digits is necessary num_digits = len(N1) precision = 3 * num_digits print "The required precision is {} digits".format(precision) gmpy2.get_context().precision = precision print "Q1)" solve_q1() print "Q2)" solve_q2() print "Q3)" solve_q3() print "Decrpyt:", decrypt()
def FermatFacotorization(n): # a = math.ceil(math.sqrt(N)) N = gmpy2.mpz(n) gmpy2.get_context().precision = 2048 a = gmpy2.sqrt(N) # print a b2 = a ** 2 - N # print b2 while not is_sqr(b2): a += 1 b2 = a ** 2 - N print a print "a is " + str(a) print "b2 is " + str(b2) # a = math.sqrt(a2) b = math.sqrt(b2) return (a + b, a - b)
def display(self, modes=False, indent="", string=False): s = "%s MPFR Data:" % indent lcl = "%s " % indent if modes: s = "%s\n%sRoundAwayZero: %s" % (s, lcl, gmpy2.RoundAwayZero) s = "%s\n%sRoundDown: %s" % (s, lcl, gmpy2.RoundDown) s = "%s\n%sRoundToNearest: %s" % (s, lcl, gmpy2.RoundToNearest) s = "%s\n%sRoundToZero: %s" % (s, lcl, gmpy2.RoundToZero) s = "%s\n%sRoundUp: %s" % (s, lcl, gmpy2.RoundUp) s = "%s\n%sfpo: %s" % (s, lcl, self.fpo) s = "%s\n%sformat: %s" % (s, lcl, self.format) # Get Base 2 mantissa and base 10 exponent # man,exp,mpfr_prec=self.fpo.digits(2) s = "%s\n%smpfr prec:%s 0x%X" % (s, lcl, self.dprec, self.dprec) s = "%s\n%smpfr sign: %s" % (s, lcl, self.isign) if not self.ic: s = "%s\n%smpfr man: %s (%s digits)" % (s, lcl, self.digits, len(self.digits)) # % (s,lcl,digits[0],len(digits[0])) s = "%s\n%smpfr exp: %s 0x%X" % (s, lcl, self.dexp, self.dexp) else: l = self.format // 8 dcd = bfp.BFPRound.decode[l] s = "%s\n%sdecode: %s" % (s, lcl, dcd) byts = fp.FP.str2bytes(self.ic) ic_sign, ic_frac, ic_exp, ic_attr = dcd.decode(byts) ic_frac = fp.rounding_mode.list2str(ic_frac, 2) s = "%s\n%sifmt big: %s" % (s, lcl, fp.FP.bytes2str(byts)) b = int.from_bytes(byts, byteorder="big", signed=False) s = "%s\n%sifmt sign:%s" % (s, lcl, ic_sign) s = "%s\n%sifmt exp: %s" % (s, lcl, ic_exp) bexp = exp + dcd.bias s = "%s\n%sifmt bias:%s 0x%X" % (s, lcl, bexp, bexp) s = "%s\n%smpfr exp: %s 0x%X" % (s, lcl, exp, exp) s = "%s\n%smpfr man: %s (%s digits)" % (s, lcl, man, len(man)) #% (s,lcl,digits[0],len(digits[0])) s = "%s\n%sifmt frac: %s (%s digits)" % (s, lcl, ic_frac, len(ic_frac)) s = "%s\n%sattr: %s" % (s, lcl, ic_attr) ctx = gmpy2.get_context() s = "%s\n%s%s" % (s, lcl, ctx) s = "%s\n" % s if string: return s print(s)
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)
def chudnovsky_bs(digits): gmpy2.get_context().precision = int(math.log2(10) * (digits + 20)) # Use binary splitting digits += 20 C = mpz(640320) C_cubed_over_24 = C**3 // 24 def bs(a, b): # a(a) = +/- (13591409 + 545140134a) # p(a) = (6a-5)(2a-1)(6a-1) # b(a) = 1 # q(a) = a^3 * C_cubed_over_24 if b - a == 1: # Directly compute if a == 0: Pab = Qab = mpz(1) else: Pab = (6*a-5) * (2*a-1) * (6*a-1) Qab = a**3 * C_cubed_over_24 Tab = Pab * (13591409 + 545140134*a) if a & 1: Tab *= -1 else: m = (a+b) // 2 # Midpoint # Recursively divide and conquer Pam, Qam, Tam = bs(a, m) Pmb, Qmb, Tmb = bs(m, b) Pab = Pam * Pmb Qab = Qam * Qmb Tab = Qmb * Tam + Pam * Tmb return Pab, Qab, Tab digits_per_term = math.log10(C_cubed_over_24/72) N = int(digits/digits_per_term + 1) P, Q, T = bs(mpz(0), mpz(N)) Q, T = mpfr(Q), mpfr(T) return (Q * 426880 * gmpy2.sqrt(mpfr(10005))) / T
def worker(xs, results, updates, trials, max): gmpy2.get_context().precision = 256 ys = (map(gmpy2.log2, x) for x in xs) polys = (scipy.interpolate.lagrange(x, y) for x, y in itertools.izip(xs, ys)) coeffs = [[int(a_i*2**64) for a_i in reversed(p.coeffs)] for p in polys] updates.put("Generated %d polynomials to test." % len(coeffs)) min_err = float('inf') min_cs = None for cs in coeffs: try: err = avg_error(cs, trials, max) if err < min_err: min_err = err min_cs = cs except Exception as exc: updates.put(str(exc)) results.put((float('inf'), None)) return updates.put("Checked %d polynomials." % len(coeffs)) results.put((min_err, min_cs))
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
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
def _init_from(self, args): # from mbrat.util import Arguments # 1st set the precision ... if not hasattr(args, 'prec'): args.prec = MBRAT_DEF_PRECISION self.prec = int(args.prec) gmpy2.get_context().precision = self.prec # ... make sure lims dict is right ... if not hasattr(args, 'lims'): self.limits = { 'low': mpc(mpfr(args.x_lo), mpfr(args.y_lo)), 'high': mpc(mpfr(args.x_hi), mpfr(args.y_hi)), } else: self.limits = args.lims # ... init the core stuff ... self._init_new(args) # ... if 'ini_d' dict provided then init more depending... if hasattr(args, 'ini_d'): if 'image' in args.ini_d: self.gen_mscreen_from_img( args.ini_d['image'] )
import gmpy2 from gmpy2 import root gmpy2.get_context().precision = 4096 import codecs e = 3 c1 = 261345950255088824199206969589297492768083568554363001807292202086148198406422015406837306712350185001004539557263392747990052517553733793783164539246862722846027251864430884218012651143187891041767278036834613455255679627575565220404720823343734717216496823882624775291829042065791328110144692179931720656184 n1 = 1001191535967882284769094654562963158339094991366537360172618359025855097846977704928598237040115495676223744383629803332394884046043603063054821999994629411352862317941517957323746992871914047324555019615398720677218748535278252779545622933662625193622517947605928420931496443792865516592262228294965047903627 c2 = 147535246350781145803699087910221608128508531245679654307942476916759248177533099119747011361428805549054451656981174660189536226806378907786889467354024644240879320253207532952949102143188764785409228498939338911381114763011074430123706304767125057179745262429033988355639559021251950099792930724833562784673 n2 = 405864605704280029572517043538873770190562953923346989456102827133294619540434679181357855400199671537151039095796094162418263148474324455458511633891792967156338297585653540910958574924436510557629146762715107527852413979916669819333765187674010542434580990241759130158992365304284892615408513239024879592309 c3 = 633230627388596886579908367739501184580838393691617645602928172655297372011548865034935604403952733958738640693591337661775300212965321256493515985362225064130164637923136989033908516462412694733923594235845265750167194852656423103420952926986457914303614556562367709542082728589329045460298763797973333272805 n3 = 1204664380009414697639782865058772653140636684336678901863196025928054706723976869222235722439176825580211657044153004521482757717615318907205106770256270292154250168657084197056536811063984234635803887040926920542363612936352393496049379544437329226857538524494283148837536712608224655107228808472106636903723 def chinese_remainder_theorem(items): # Determine N, the product of all n_i N = 1 for a, n in items: N *= n # Find the solution (mod N) result = 0 for a, n in items: m = N // n r, s, d = extended_gcd(n, m) if d != 1: raise "Input not pairwise co-prime" result += a * s * m # Make sure we return the canonical solution. return result % N
#!/usr/bin/env python #Author : Karthik C #////////////////////////////////////////////////// #Code developed to genetare ADS-B message////////// #////////////////////////////////////////////////// import math import sys import gmpy2 #multi precision module from gmpy2 import mpz,mpq,mpfr,mpc import numpy from numpy import * #-------------Globals----------------------------------- gmpy2.get_context().precision = 32#set gmpy precision to 128 bits Dlat0 = 6 # Even message Dlat1 = mpfr(6.101694915254237288135593220339) # Odd message pi = mpfr(gmpy2.const_pi(),56) airID = 0x8D # bit 1 to 5 DF format 17 and 6 to 8 CA type 3 altitude = 0 evenMsg = mpz(1) oddMsg = mpz(1) CRCOdd = mpz(1) CRCEven = mpz(1) #-----------For testing ------------------------- t_aid = 'ab7444' t_alt = 40000 t_lat = mpfr(49.925827) t_lon = mpfr(89.193542)
import numpy import gmpy2 import math from collections import defaultdict from gmpy2 import mpz gmpy2.get_context().precision=10000 N = 179769313486231590772930519078902473361797697894230657273430081157732675805505620686985379449212982959585501387537164015710139858647833778606925583497541085196591615128057575940752635007475935288710823649949940771895617054361149474865046711015101563940680527540071584560878577663743040086340742855278549092581 N=179769313486231590772930519078902473361797697894230657273430081157732675805505620686985379449212982959585501387537164015710139858647833778606925583497541085196591615128057575940752635007475935288710823649949940771895617054361149474865046711015101563940680527540071584560878577663743040086340742855278549092581 N=648455842808071669662824265346772278726343720706976263060439070378797308618081116462714015276061417569195587321840254520655424906719892428844841839353281972988531310511738648965962582821502504990264452100885281673303711142296421027840289307657458645233683357077834689715838646088239640236866252211790085787877 N=720062263747350425279564435525583738338084451473999841826653057981916355690188337790423408664187663938485175264994017897083524079135686877441155132015188279331812309091996246361896836573643119174094961348524639707885238799396839230364676670221627018353299443241192173812729276147530748597302192751375739387929 N= mpz(N)*6 A=gmpy2.ceil(gmpy2.sqrt(gmpy2.mpz(N))) B=numpy.powmod(2,20,N) for i in range(0,B+1): print i #x=mpz(A*A) -N A=mpz(A) z=mpz(A)*mpz(A) #print mpz(z)+1 y=mpz(z)-mpz(N) x=gmpy2.sqrt(gmpy2.mpz(y)) p=mpz(A)-mpz(x) q=mpz(A)+mpz(x) #print p #print mpz(p)
#!/usr/bin/python2 import gmpy2 #import matplotlib.pyplot as plt import os import bisect from numpy import linspace # gmpy2 precision initialization BITS = (1 << 10) BYTES = BITS/8 gmpy2.get_context().precision = BITS # a whole lotta bits def random(): seed = int(os.urandom(BYTES).encode('hex'), 16) return gmpy2.mpfr_random(gmpy2.random_state(seed)) # Useful constants as mpfr PI = gmpy2.acos(-1) LOG2E = gmpy2.log2(gmpy2.exp(1)) LN2 = gmpy2.log(2) # Same, as 192.64 fixedpoint FX_PI = int(PI * 2**64) FX_LOG2E = int(LOG2E * 2**64) FX_LN2 = int(LN2 * 2**64) FX_ONE = 1 << 64 ## The index of a poly is the power of x, ## the val at the index is the coefficient. ## ## An nth degree poly is a list of len n + 1. ## ## The vals in a poly must all be floating point ## numbers.