def prime_test_miller_rabin(p, k=25): """ Test for primality by Miller-Rabin Stronger than Solovay-Strassen's test """ if p < 2: return False if p <= 3: return True if p & 1 == 0: return False # p - 1 = 2**s * m s, m = extract_prime_power(p - 1, 2) for j in range(k): a = random.randint(2, p - 2) if gcd(a, p) != 1: return False b = pow(a, m, p) if b in (1, p - 1): continue for i in range(s): b = pow(b, 2, p) if b == 1: return False if b == p - 1: # is there one more squaring left to result in 1 ? if i < s - 1: break # good else: return False # bad else: # result is not 1 return False return True
def __init__(self, numerator=1, denominator=1): if denominator == 0: raise Exception( "The denominator cannot be zero, please reenter another number!" ) else: g = gcd(numerator, denominator) self.numerator = numerator / g self.denominator = denominator / g
def Rho(n): fList = [f(2)] for i in xrange(2, n): fList.append(f(fList[-1])) factor = gcd(fList[(2 * (i / 2)) - 1] - fList[(i / 2) - 1], n) if i % 2 == 0 and factor > 1: break return n / factor
def pollardP(n): #pollardP is factoring algorithm which finds a prime factor of n #print("pollardP", n) # ^ is debugging for when this is used in other functions if isPrime(n): #pollardP will not terminate if given a prime print("Prime was passed into pollardP") return #generate a random polynomial equation #I use a quadratic with coefficients ∈ [-10, 10] a = randrange(-10, 10) b = randrange(-10, 10) c = randrange(-10, 10) def f(x): return a * x * x + b * x + c #set up vars for loop x = 2 y = 2 d = 1 while True: #print(x, y, a, b, c, d) #debugging #set x to be f(x), y to be f^2(y), and d to be the gcd of (the difference between x and y) and (n) #(this is all done modulo n) #this means that eventually the difference between x and y shares a common factor n, and if so, we factored n x = f(x) % n y = f(f(y)) % n d = gcd(abs(x - y), n) if d == n: #if d = n, then we need to restart the algorithm a = randrange(-10, 10) b = randrange(-10, 10) c = randrange(-10, 10) def f(x): return a * x * x + b * x + c x = 2 y = 2 elif d != 1: #if d is not 1 or n, then we factored n if d * int( n / d ) == n: #I am having some wierd bugs with it not factoring correctly, this is my bad fix before I can debug better return d, int(n / d) else: return pollardP(n)
def jug_problem(a, b, k): class Jug(object): def __init__(self, capacity): self.capacity = capacity self.filled_with = 0 def free_space(self): return self.capacity - self.filled_with def is_full(self): return self.filled_with == self.capacity def is_empty(self): return self.filled_with == 0 def fill(self): self.filled_with = self.capacity def empty(self): self.filled_with = 0 def fill_from(self, jug): if jug.filled_with <= self.free_space(): self.filled_with += jug.filled_with jug.empty() else: jug.filled_with -= self.free_space() self.filled_with = self.capacity def __str__(self): return "{}:{}".format(self.filled_with, self.capacity) jug1, jug2 = Jug(a), Jug(b) solution = [] def solve(jug1, jug2, k): if jug2.filled_with != k: if jug2.is_full(): jug2.empty() elif jug1.is_empty(): jug1.fill() else: jug2.fill_from(jug1) solution.append((str(jug1), str(jug2))) solve(jug1, jug2, k) if k % gcd(a, b) == 0 and k <= b: solve(jug1, jug2, k) print( "->".join(map(str, solution))) else: print("Problem is not solvable with these arguments.")
def printAns(a, b): g = gcd(a, b) if b > a: temp = valXY[0] valXY[0] = valXY[1] valXY[1] = temp if a * getX() > b * getY(): valXY[1] = -valXY[1] else: valXY[0] = -valXY[0] print("x = %d + %dt" % (getX(), int(b / g))) print("y = %d - %dt" % (getY(), int(a / g)))
def RSA(m): #example value p = 17 p = random.randint(2**12, 2**13) #no issues while mil_rab(p, 2) != 1: p = random.randint(2**12, 2**13) #pPrime == True # example value q = 19 q = random.randint(2**20, 2**21) #no issues while mil_rab(q,2) != 1: q = random.randint(2**20, 2**21) #qPrime == True n = p * q #no issues print "Public Key n: " + str(n) secretD = euler_phi(p,q) #no issues print "Euler D: " + str(secretD) d = -1 while(d < 0): #can remove this and program will work with infinite recursion however e = random.randint(2**20, 2**21) print("e: " + str(e)) while gcd(e, secretD) != 1: e = random.randint(2**20, 2**21) print("New e: " + str(e)) d = xgcd(e, secretD)[1] print("D: " + str(d)) c = binary_exp(m,e,n) print ("C: " + str(c)) decrypt = binary_exp(c,d,n) print m, decrypt
def Rho(n): factors = {} i = 1 x = 1 d = 1 while d == 1: #Calculate x[i] factors[i] = f(x,n) #Calculate x[i+1] factors[i+1] = f(factors[i],n) #find the gcd d = gcd(abs(factors[(i+1)/2] - factors[i+1]),n) #if not relatively prime return d if d > 1: return d #continue iteration else: x = factors[i+1] i+=2
# if n % i == 0: # divisors.append(i) # if i != n // i: # divisors.append(n//i) # divisors.sort(reverse=True) # return divisors import gcd K = int(input()) ans = 0 for a in range(1, K + 1): for b in range(1, K + 1): for c in range(1, K + 1): ans += gcd(gcd(a, b), c) print(ans) exit() d = {} vals = [] for i in range(1, K + 1): for j in range(1, K + 1): nums = [i, j] nums.sort() key = str(i) + '-' + str(j) if key in d: vals.append(d[key]) else: val = gcd(i, j) d[key] = val
def lcm(a, b): gcd_ = gcd(a, b) return (int(a / gcd_) * b)
import math import gcd for t in range(int(input())): n = int(input()) arr = list(map(int, input().split())) prd, rest = 1, 1 for i in arr: prd *= i for i in range(len(arr)): rest *= i prd = prd // arr[i] if(gcd(rest, prd) == 1): print(i+1) break
def test_gcd(): """test greatest common divisor""" assert gcd(1, 1) == 1 assert gcd(9, 12) == 3 assert gcd(12, 9) == 3
if max(a)==min(a): a[0] else: gcd_2(a) def gcd_3(a,b): if min(a,b) == 0: return max(a,b) return gcd_3(b,a%b) a = [] for i in args: a.append(i) gcd_2(a) return a[0] print(gcd(25,10)) gcd(40,20,30,40) #문제2. 탐욕 알고리즘을 이용하여 지불해야 하는 금액을 가장 적은 수의 화폐로 지불하시오.(1원 50원 100원 / 362) def greedy(num): cash=[100,50,1] j=[] for i in cash: res = divmod(num,i) num = res[1] j.append(res[0]) return j print(greedy(400))
def gcd(num1,num2): if num2==0: return num1 else: gcd(num2,num1%num2) return num1
def lcm(a, b): return a * b // gcd(a, b)
elif oper == 'ojld': while 1: a = int(input('Pleaase enter your number -> '), 16) m = 0b100011011 tmp = ojld(a, m) print('Inverse element is ' + bin(tmp) + ' ' + hex(tmp)) oper_1 = input('Go on ? [y/n]') if oper_1 == 'n': break elif oper == 'gcd': while 1: a, b = input("Please enter two number -> ").split() a, b = int(a, 16), int(b, 16) tmp = gcd(a, b) print("gcd is " + bin(tmp) + ' ' + hex(tmp)) oper_1 = input('Go on ? [y/n]') if oper_1 == 'n': break elif oper == 'extgcd': while 1: a, b = input("Please enter two number -> ").split() a, b = int(a, 16), int(b, 16) tmp = ojld(a, b) oper_1 = input('Go on ? [y/n]') if oper_1 == 'n': break elif oper == 'prime':
def reduce(x,y): d = gcd(x,y) return (x/d,y/d)
from gcd import * print(gcd(10, 20)) print(a) foo()
def lcm(a, b): ans = b * (a / gcd(a, b)) print(int(ans))
from gcd import * print gcd(8,20)
import math import gcd def get_lcm(num1, num2): return ( num1*num2 ) // gcd(num1, num2) class Frac: def __init__(self, numerator_, denominator_) gcd_ = gcd(numerator_, denominator_) self.numertr = numerator_ // gcd_ self.denomntr = denominator_ // gcd_ def __repr__(self) return 'Frac({}/{})'.format(self.numertr, self.denomntr) def __str__(self) return '{}/{}'.format(self.numertr, self.denomntr) def __сopy__(self) return Frac(self.numertr, self.denomntr) def normalize(self) gcd_ = gcd(self.numertr, self.denomntr) self.numertr // gcd_ self.denomntr // gcd_ def __iadd__(self, rhs) lcm_ = get_lcm(self.denominator, rhs.denomntr) self.numerator = self.numerator * (lcm // self.denomntr) + rhs.numertr * (lcm // rhs.denomntr) self.denomntr = lcm_
def PhiFunc(n): Philist = [] for i in xrange(1,n): if(gcd(n,i)==1): Philist.append(i) return Philist
def test_hyp_gcd(x, y): if (gcd(x, y) != 0): assert ((x % gcd(x, y) == 0) and (y % gcd(x, y) == 0))
def get_lcm(num1, num2): return ( num1*num2 ) // gcd(num1, num2)
def test_gcd(a, b, expected): assert (gcd(a, b) == expected)