def AGM(a, b): """ Arithmetic-Geometric Mean. """ x = (a+b) * 0.5 y = math.sqrt(a*b) while abs(x-y) > y*1e-15: x, y = (x+y) * 0.5, math.sqrt(x*y) return x
def AGM(a, b): """ Arithmetic-Geometric Mean. """ x = (a + b) * 0.5 y = math.sqrt(a * b) while abs(x - y) > y * 1e-15: x, y = (x + y) * 0.5, math.sqrt(x * y) return x
def aks(n): """ AKS ( Cyclotomic Congruence Test ) primality test for a natural number. Input: a natural number n ( n > 1 ). Output: n is prime => return True n is not prime => return False. """ import nzmath.multiplicative as multiplicative if arith1.powerDetection(n)[1] != 1: #Power Detection return False lg = math.log(n, 2) k = int(lg * lg) start = 3 while 1: d = gcd.gcd(start, n) if 1 < d < n: return False x = n % start N = x for i in range(1, k + 1): if N == 1: break N = (N * x) % start if i == k: r = start break start += 1 d = gcd.gcd(r, n) if 1 < d < n: return False if n <= r: return True e = multiplicative.euler(r) #Cyclotomic Conguence e = math.sqrt(e) e = int(e * lg) for b in range(1, e + 1): f = array_poly.ArrayPolyMod([b, 1], n) total = array_poly.ArrayPolyMod([1], n) count = n while count > 0: if count & 1: total = total * f total = _aks_mod(total, r) f = f.power() f = _aks_mod(f, r) count = count >> 1 total_poly = total.coefficients_to_dict() if total_poly != {0: b, n % r: 1}: return False return True
def e2(x): """ 0 = x[0] + x[1]*t + x[2]*t**2 """ c, b, a = x d = b**2 - 4 * a * c if d >= 0: sqrtd = math.sqrt(d) else: sqrtd = cmath.sqrt(d) return ((-b + sqrtd) / (2 * a), (-b - sqrtd) / (2 * a))
def e2(x): """ 0 = x[0] + x[1]*t + x[2]*t**2 """ c, b, a = x d = b**2 - 4*a*c if d >= 0: sqrtd = math.sqrt(d) else: sqrtd = cmath.sqrt(d) return ((-b + sqrtd)/(2*a), (-b - sqrtd)/(2*a))
def floorsqrt(a): """ Return the floor of square root of the given integer. """ if a < 2 ** 59: return int(math.sqrt(a)) else: b_old = a b = pow(10, log(a, 10)//2 + 1) while b_old > b: b_old, b = b, (b+a//b)//2 return b_old
def floorsqrt(a): """ Return the floor of square root of the given integer. """ if a < (1 << 59): return int(math.sqrt(a)) else: # Newton method x = pow(10, (log(a, 10) >> 1) + 1) # compute initial value while True: x_new = (x + a // x) >> 1 if x <= x_new: return x x = x_new
def sqrt(x, err=defaultError): """ sqrt(x [,err]) returns the positive square root of real number x. """ rx = rational.Rational(x) if rx.numerator < 0: raise ValueError("negative number is passed to sqrt") if rx.numerator == 0: return rational.Integer(0) if err <= defaultError: n = rx.denominator * rx.numerator rt = rational.Rational(arith1.floorsqrt(n), rx.denominator) newrt = (rt + rx / rt) / 2 while not err.nearlyEqual(rt, newrt): rt = newrt newrt = (rt + rx / rt) / 2 else: newrt = rational.Rational(math.sqrt(x.toFloat())) return newrt