def elemop(N=1000): r''' (Takes about 40ms on a first-generation Macbook Pro) ''' for i in range(N): assert a+b == 579 assert a-b == -333 assert b*a == a*b == 56088 assert b%a == 87 assert divmod(a, b) == (0, 123) assert divmod(b, a) == (3, 87) assert -a == -123 assert pow(a, 10) == 792594609605189126649 assert pow(a, 7, b) == 99 assert cmp(a, b) == -1 assert '7' in str(c) assert '0' not in str(c) assert a.sqrt() == 11 assert _g.lcm(a, b) == 18696 assert _g.fac(7) == 5040 assert _g.fib(17) == 1597 assert _g.divm(b, a, 20) == 12 assert _g.divm(4, 8, 20) == 3 assert _g.divm(4, 8, 20) == 3 assert _g.mpz(20) == 20 assert _g.mpz(8) == 8 assert _g.mpz(4) == 4 assert a.invert(100) == 87
def __init__(self, n, n_party, n_threshold, combineShareConstant): self.n, self.l, self.w, self.combineShareConstant = n, n_party, n_threshold, combineShareConstant self.n2 = n**2 self.max_int = n // 3 - 1 self.k = n.bit_length() self.delta = gmpy2.fac(n_party) pass
def factor_prime(prime): # p - 1 is 37-smooth base = 2 k_sm = 37 # pow(base,k_sm!) mod prime a = gmpy2.powmod(base, gmpy2.fac(k_sm), prime) # gcd(r_k - 1, prime) p = gmpy2.gcd(a-1, prime) # get second factor of prime q = (prime / p) # make sure factors (pq) are prime if (gmpy2.is_prime(p) and gmpy2.is_prime(q)): print "p = ", p print "q = ", q # make sure n = p*q = prime number n = gmpy2.mul(p,q) if (n == prime): print "n = ", gmpy2.mul(p,q) return
def perm(n, k): # k = float(k) # n = float(n) # if k > n: # return 0 # if k < 0: # raise ValueError("k must be non-negative") # return float(fac(n)) / float(fac(n - k)) if k > n: return 0 if k < 0: raise ValueError("k must be non-negative") return gmp.fac(n) / (fac(k) * fac(n - k))
def get_ith(n): n = n - 1 result = '' while n != 0: size = len(NUMS) - 1 div, mod = divmod(n, gmpy2.fac(size)) result += str(NUMS[div]) n = mod del (NUMS[div]) for i in range(len(NUMS)): result += str(NUMS[i]) return result
def fac(num): """ Cached frequently computed factorial. Parameters ---------- num : int Number of which the factorial is computed. Returns ------- gmpy2.mpz Very precise factorial of `num`. """ return gmpy2.fac(misc._int(num))
def william_p1(n, process_id): # this algorithm technically works but literally none of the modulos were p+1 so idk # choose a B (work limit) to start with if gmpy2.bit_length(gmpy2.mpz(n)) <= 2044: work_limit = pow(n, (1 / 6)) else: work_limit = gmpy2.div(n, 27) threshold = 3 previous_sub2 = 2 # A needs to be greater than 2 to start with so we therefore start with 3 A = process_id + 3 previous = A counter = 0 # if the counter ever reaches m, terminate while counter != threshold: counter += 1 # current = (a^(current-1) - current-2) % n) current = (((A**previous) - previous_sub2) % n) # move the previous variables forward previous_sub2 = previous previous = current d = gmpy2.gcd(current - 2, n) if d != 1 and d != n: # calculate the factorial of m mult = gmpy2.fac(threshold) if DEBUG: print(d, mult) # check to see if we've found the terminating conditions for p + 1 if gmpy2.f_mod(mult, d): return d else: # increment threshold by 1 if we haven't found anything threshold += 1 if threshold > work_limit: return 1 return 1
import gmpy2 as _g import time print "Typical expected results would be:", """ D:\PySym>python timing.py Factorial of 10000 took 0.0619989238859 (35660 digits) Fibonacci of 10000 took 0.000744228458022 (2090 digits) Factorial of 100000 took 4.44311764676 (456574 digits) Fibonacci of 100000 took 0.022344453738 (20899 digits) Factorial of 1000000 took 152.151135367 (5565709 digits) Fibonacci of 1000000 took 0.670207059778 (208988 digits) """ print "Actual timings and results...:" for i in (10000, 100000, 1000000): start = time.clock() x = _g.fac(i) stend = time.clock() print "Factorial of %d took %s (%d digits)" % (i, stend - start, x.num_digits()) start = time.clock() x = _g.fib(i) stend = time.clock() print "Fibonacci of %d took %s (%d digits)" % (i, stend - start, x.num_digits())
def p19(n): return reduce(lambda a, b: a + b, list(map(int, list(str(fac(n))))))
from gmpy2 import fac w, h = 20, 20 result = fac(w + h) / (fac(w) * fac(h)) print(result)
def big_num(): operator = request.values.get('operator') result = '1' try: if operator == 'FACT' or operator == 'isPrime': p = gmpy2.mpz(int(request.values.get('p'))) if not p: resu = {'code': 10001, 'message': '参数不能为空!'} return json.dumps(resu, ensure_ascii=False) if operator == 'FACT': #p的阶层 result = gmpy2.fac(p) elif operator == 'isPrime': #判断p是否是素数 result = gmpy2.is_prime(p) elif operator == 'MULMN' or operator == 'POWMN': p = gmpy2.mpz(int(request.values.get('p'))) q = gmpy2.mpz(int(request.values.get('q'))) n = gmpy2.mpz(int(request.values.get('n'))) if not p and not q and not n: resu = {'code': 10001, 'message': '参数不能为空!'} return json.dumps(resu, ensure_ascii=False) if operator == 'POWMN': #计算p**q mod n result = gmpy2.powmod(p, q, n) elif operator == 'MULMN': #计算p*q mod n result = gmpy2.modf(gmpy2.mul(p, q), n) else: p = gmpy2.mpz(int(request.values.get('p'))) q = gmpy2.mpz(int(request.values.get('q'))) if not p and not q: resu = {'code': 10001, 'message': '参数不能为空!'} return json.dumps(resu, ensure_ascii=False) if operator == 'ADD': #相加 print('good') result = gmpy2.add(p, q) elif operator == 'SUB': #相减 result = gmpy2.sub(p, q) elif operator == 'MUL': #相乘 result = gmpy2.mul(p, q) elif operator == 'DIV': #相除 result = gmpy2.div(p, q) elif operator == 'MOD': #取余 result = gmpy2.f_mod(p, q) elif operator == 'POW': result = gmpy2.powmod(p, q) elif operator == 'GCD': #最大公因数 result = gmpy2.gcd(p, q) elif operator == 'LCM': result = gmpy2.lcm(p, q) elif operator == 'OR': #或 result = p | q elif operator == 'AND': #与 result = p & q elif operator == 'XOR': #抑或 result = p ^ q elif operator == 'SHL': #左移 result = p << q elif operator == 'SHR': #右移 result = p >> q resu = {'code': 200, 'result': str(result)} return json.dumps(resu, ensure_ascii=False) except: resu = {'code': 10002, 'message': '异常。'} return json.dumps(resu, ensure_ascii=False)
def search(f, box, n, m, batch, resfile, rho0=0.5, p=1.0, executor=get_default_executor()): """ Minimize given expensive black-box function and save results into text file. Parameters ---------- f : callable The objective function to be minimized. box : list of lists List of ranges for each parameter. n : int Number of initial function calls. m : int Number of subsequent function calls. batch : int Number of function calls evaluated simultaneously (in parallel). resfile : str Text file to save results. rho0 : float, optional Initial "balls density". p : float, optional Rate of "balls density" decay (p=1 - linear, p>1 - faster, 0<p<1 - slower). executor : callable, optional Should have a map method and behave as a context manager. Allows the user to use various parallelisation tools as dask.distributed or pathos. """ # space size d = len(box) # adjusting the number of function calls to the batch size if n % batch != 0: n = n - n % batch + batch if m % batch != 0: m = m - m % batch + batch # go from normalized values (unit cube) to absolute values (box) def cubetobox(x): return [box[i][0]+(box[i][1]-box[i][0])*x[i] for i in range(d)] # generating R-sequence points = np.zeros((n, d+1)) points[:, 0:-1] = rseq(n, d) # initial sampling for i in range(n//batch): with executor() as e: points[batch*i:batch*(i+1), -1] = list(e.map(f, list(map(cubetobox, points[batch*i:batch*(i+1), 0:-1])))) # normalizing function values fmax = max(abs(points[:, -1])) points[:, -1] = points[:, -1]/fmax # volume of d-dimensional ball (r = 1) if mpz(d) % 2 == 0: v1 = np.pi**(d/2)/fac(d/2) else: v1 = 2*(4*np.pi)**((d-1)/2)*fac((d-1)/2)/fac(d) # subsequent iterations (current subsequent iteration = i*batch+j) for i in range(m//batch): # sampling next batch of points fit = rbf(points) points = np.append(points, np.zeros((batch, d+1)), axis=0) for j in range(batch): r = ((rho0*((m-1.-(i*batch+j))/(m-1.))**p)/(v1*(n+i*batch+j)))**(1./d) cons = [{'type': 'ineq', 'fun': lambda x, localk=k: np.linalg.norm(np.subtract(x, points[localk, 0:-1])) - r} for k in range(n+i*batch+j)] while True: minfit = op.minimize(fit, np.random.rand(d), method='SLSQP', bounds=[[0., 1.]]*d, constraints=cons) if np.isnan(minfit.x)[0] == False: break points[n+i*batch+j, 0:-1] = np.copy(minfit.x) with executor() as e: points[n+batch*i:n+batch*(i+1), -1] = list(e.map(f, list(map(cubetobox, points[n+batch*i:n+batch*(i+1), 0:-1]))))/fmax # saving results into text file points[:, 0:-1] = list(map(cubetobox, points[:, 0:-1])) points[:, -1] = points[:, -1]*fmax points = points[points[:, -1].argsort()] labels = [' par_'+str(i+1)+(7-len(str(i+1)))*' '+',' for i in range(d)]+[' f_value '] np.savetxt(resfile, points, delimiter=',', fmt=' %+1.4e', header=''.join(labels), comments='')
#!/usr/bin/env python3 import gmpy2 from decimal import Decimal N = int(gmpy2.fac(333)) #N = 10334465434588059156093965538297516550622260041682062823432902469783188597914276568552700194849877929894375950252570477080418352732597658745665925604704669227133726477243854317836635130694123893711638533001980496229875665476598568821806170303765540489814402234159901540440432134155844542962445153646330595588291605924429211352279943471372817279938720974895260387784578239150931816946786416232516666251965421919651838044618050991294403546958930745419743836966520198735201123255884089263272829846640538826979843642885775791641575109178753509580001660392092396798648924375401024147883702298145910046889402880394195369984000000000000000000000000000000000000000000000000000000000000000000000000000000000 sN = int(gmpy2.isqrt(N)) #sN = 3214726338988757399964463840205273148284735043324463579894976679845078166928105412104944973948893914339037572694382785661727648297539107767478128297633669341356440278480314502443731079340424764653103468238563073341496690901434197268615240607985890327844073738551115260849983966971570699838147501655616953786428037017304945538845583678438817092853062 k = int(input("Enter number: ")) goodness = Decimal(abs(k - sN)) / sN if k and N % k == 0 and goodness < 1e-8: print(open('/home/eulernt/flag.txt').read()) elif k and N % k == 0 and goodness < 1e-4: print("Good work! You're getting there.") else: print("Nope!")
from gmpy2 import fac FACS = [int(fac(i)) for i in range(10)] memochains = {} def sum_fac_digits(num): return sum(FACS[int(c)] for c in str(num)) def make_key(num): return ''.join(sorted(str(num).replace('0', '1'))) def chain_length(num): key = make_key(num) if key in memochains: return memochains[key] chain = [] while (num not in chain) and (len(chain) <= 60): chain.append(num) num = sum_fac_digits(num) memochains[key] = len(chain) return len(chain) chain_count = 0 for n in range(1, 10**6): if chain_length(n) == 60: chain_count += 1 print(chain_count)
def __call__(self, i): return gmpy2.fac(i)
def gen_key(bitlen, n_party, n_threshold, saveToFile=False, verbose=False): assert math.log2( bitlen) >= 8, "Bit-length of n should not be less than 256." bitlen >>= 1 if verbose: print( "Start generating public and private keys for threshold Paillier ...", end=" ") res = {} def __getSafePrimes(n_len): rng = secrets.SystemRandom() prime_ = gmpy2.mpz(rng.getrandbits(n_len - 1)) prime_ = gmpy2.bit_set(prime_, n_len - 2) while True: prime_ = gmpy2.next_prime(prime_) prime = 2 * prime_ + 1 if gmpy2.is_prime(prime, 25): break return prime_, prime start = time.process_time() p1, p = __getSafePrimes(bitlen) while True: q1, q = __getSafePrimes(bitlen) if p1 != q1 and p1 != q and q1 != p: break n, m = p * q, p1 * q1 nm = n * m d = m * gmpy2.invert(m, n) a = [d] a = a + [ gmpy2.mpz_random(gmpy2.random_state(secrets.randbelow(sys.maxsize)), nm) for i in range(1, n_threshold) ] delta = gmpy2.fac(n_party) combineShareConstant = gmpy2.invert((4 * delta**2) % n, n) shares = [gmpy2.mpz(0)] * n_party for index in range(n_party): fx = [a[i] * ((index + 1)**i) for i in range(n_threshold)] shares[index] += sum(fx) % nm for i in range(n_party): res[i + 1] = PaillierThresholdPrivateKey(n, n_party, n_threshold, combineShareConstant, i + 1, shares[i]) end = time.process_time() if verbose: print("finished. Time elapsed: %g seconds." % (end - start)) if saveToFile: if verbose: print("Saving keys to files ...") keys = { 'n': str(n), 'l': n_party, 'w': n_threshold, 'combineShareConstant': str(combineShareConstant) } for i in range(n_party): keys.update({'si': str(shares[i]), 'id': i + 1}) if not os.path.isdir("encryption/keys/"): os.mkdir("encryption/keys/") with open("encryption/keys/" + str(i + 1) + ".key", 'w') as f: json.dump(keys, f) return res
def wilson_is_prime(n): return ((fac(n-1)+1) % n) == 0
def regions_discrete(ra, rd, rc, k, pf_plus, pf_minus, precision=1000): """ Construct (px, px_tilde, px/px_tilde) regions used to find the certified radius for general discrete data. Note: if pf_plus = pf_minus any combination of ra+rd+rc=r gives the same result. ra: int Number of zeros changed to non-zeros from x to x_tilde. rd : int Number of non-zeros changed to zeros from x to x_tilde. rc : int Number of non-zeros changed to other non-zero values from x to x_tilde. k: int Number of discrete categories. pf_plus : float, 0 <= p_plus <= 1 The probability to flip a zero to a non-zero. pf_minus: float, 0 <= p_plus <= 1 The probability to flip a non-zero to a zero. precision: int Numerical precision for floating point calculations. """ with gmpy2.context(precision=precision): pf_plus, pf_minus = gmpy2.mpfr(pf_plus), gmpy2.mpfr(pf_minus) one = gmpy2.mpfr(1) ra, rd, rc = int(ra), int(rd), int(rc) a0 = (one - pf_plus) b0 = pf_plus / (k - 1) c0 = one - a0 - b0 dist_0 = [a0, b0, c0] a1 = (one - pf_minus) b1 = pf_minus / (k - 1) c1 = one - a1 - b1 dist_1 = [a1, b1, c1] regions = defaultdict(float) for triplet in product(triplets(ra, k), triplets(rd, k), triplets(rc, k)): q0, p0, m0 = triplet[0] q1, p1, m1 = triplet[1] q2, p2, m2 = triplet[2] ratio = 1 ratio *= (a0 / b1)**(q0 - p1) ratio *= (b0 / a1)**(p0 - q1) ratio *= (c0 / c1)**(m0 - m1) ratio *= (a1 / b1)**(q2 - p2) # compute the product of three multinomial distributions px = 1 for (qi, pi, mi), ri, dist in zip(triplet, [ra, rd, rc], [dist_0, dist_1, dist_1]): px *= dist[0]**qi px *= dist[1]**pi px *= dist[2]**mi px *= gmpy2.fac(ri) / gmpy2.fac(qi) / gmpy2.fac(pi) / gmpy2.fac(mi) regions[float(ratio)] += px regions = np.array(list(regions.items())) srt = regions[:, 0].argsort()[::-1] return np.column_stack( (regions[srt, 1], regions[srt, 1] / regions[srt, 0], regions[srt, 0]))
def digit_fac(n): n = str(n) temp = 0 for i in range(len(n)): temp += gmpy2.fac(int(n[i])) return temp
from gmpy2 import fac # starting from index 0, so millionth perm has index 999999 n = 10 ** 6 - 1 s = list("0123456789") perm = "" while len(perm) < 10: d = fac(len(s) - 1) pos, n = divmod(n, d) perm += s[pos] s.remove(perm[-1]) print(perm)
#!/usr/bin/env python3 import gmpy2 from decimal import Decimal N = int(gmpy2.fac(333)) sN = int(gmpy2.isqrt(N)) lastgoodness = 2**32 for i in range(333): k = int(gmpy2.fac(i)) goodness = Decimal(abs(k - sN)) / sN print(goodness) if goodness > lastgoodness: i = i - 1 break lastgoodness = goodness k = int(gmpy2.fac(i)) factor = i - 1 direction = 0 while not (N % k == 0 and goodness < 1e-8): x = int(gmpy2.fac(factor)) if direction == 0: k = k + x else: k = k - x
import gmpy2 as _g import time print("Typical expected results would be:",""" D:\PySym>python timing.py Factorial of 10000 took 0.0619989238859 (35660 digits) Fibonacci of 10000 took 0.000744228458022 (2090 digits) Factorial of 100000 took 4.44311764676 (456574 digits) Fibonacci of 100000 took 0.022344453738 (20899 digits) Factorial of 1000000 took 152.151135367 (5565709 digits) Fibonacci of 1000000 took 0.670207059778 (208988 digits) """) print("Actual timings and results...:") for i in (10000,100000,1000000): start=time.time() x=_g.fac(i) stend=time.time() print("Factorial of %d took %s (%d digits)" % ( i, stend-start, x.numdigits())) start=time.time() x=_g.fib(i) stend=time.time() print("Fibonacci of %d took %s (%d digits)" % ( i, stend-start, x.numdigits()))
from gmpy2 import fac digits = [int(t, 10) for t in str(fac(100))] total = sum(digits) print(total)