def lattice(m): square_num = set(i**2 for i in range(int(20000**0.5))) # Precalculate triangle values tri_table = [[[0]*101 for i in range(101)] for j in range(101)] for a in range(101): for h in range(101): for c in range(101): A2 = (a+c)*h B = gcd(a, h) + gcd(h, c) + a + c tri_table[a][h][c] = (A2 - B)//2 + 1 s = 0 for a in range(1, m+1): for c in range(1, a+1): # Symmetry case counter rc = 2 if c!=a else 1 # a,c symmetry for b in range(1, a+1): rcb = 2*rc if b!=a else rc # a, b symmetry # Upper triangle + horizontal edge correction abc_ = tri_table[a][b][c] + a + c - 1 for d in range(1, b+1): if abc_ + tri_table[a][d][c] in square_num: s += 2*rcb if d!=b else rcb # b,d symmetry return s
def make_salt(digest): salt = (get_cation(digest), get_anion(digest)) paren = [False, False] subscript = "₀ ₂₃₄₅₆₇₈₉" for sub in subscript: if sub in salt[0][1]: paren[0] = True if sub in salt[1][1]: paren[1] = True if sum(1 for c in salt[0][1] if c.isupper()) is not 1: paren[0] = True if sum(1 for c in salt[1][1] if c.isupper()) is not 1: paren[1] = True name = salt[0][0] + " " + salt[1][0] formula_parts = [salt[0][1], salt[1][1], salt[1][2], salt[0][2]] if paren[0]: formula_parts[0] = "(" + formula_parts[0] + ")" if paren[1]: formula_parts[1] = "(" + formula_parts[1] + ")" formula_parts[2] = formula_parts[2]//fractions.gcd(formula_parts[2], formula_parts[3]) formula_parts[3] = formula_parts[3]//fractions.gcd(formula_parts[2], formula_parts[3]) formula = ''.join([f for f in (formula_parts[0] + subscript[formula_parts[2]] + formula_parts[1] + subscript[formula_parts[3]]) if not f == ' ']) return (name,formula)
def keygen(N, public=None): ''' Generate public and private keys from primes up to N. Optionally, specify the public key exponent (65537 is popular choice). >>> pubkey, privkey = keygen(2**64) >>> msg = 123456789012345 >>> coded = pow(msg, *pubkey) >>> plain = pow(coded, *privkey) >>> assert msg == plain ''' # http://en.wikipedia.org/wiki/RSA prime1 = gen_prime(N) prime2 = gen_prime(N) composite = prime1 * prime2 totient = (prime1 - 1) * (prime2 - 1) if public is None: while True: private = randrange(totient) if gcd(private, totient) == 1: break public = multinv(totient, private) else: private = multinv(totient, public) assert public * private % totient == gcd(public, totient) == gcd(private, totient) == 1 assert pow(pow(1234567, public, composite), private, composite) == 1234567 return KeyPair(Key(public, composite), Key(private, composite))
def _lambda(P, other=None): if other: Q = other a = (Q.y - P.y) % P.curve.field b = Q.x - P.x aux = abs(a) d = gcd(aux, b) a /= d; b /= d a = (a + P.curve.field) % P.curve.field if (a % b != 0): b = invmod(b, P.curve.field) return a * b % P.curve.field return a / b else: a = (3*P.x*P.x + P.curve.A) % P.curve.field b = 2*P.y aux = abs(a) d = gcd(aux, b) a /= d; b /= d a = (a + P.curve.field) % P.curve.field if (a % b != 0): b = invmod(b, P.curve.field) return a * b % P.curve.field return a / b
def factor(n, b1, b2, m, s): u = (s * s - 5) % n v = (4 * s) % n an = (pow(v - u, 3, n) * (3 * u + v)) % n ad = (4 * pow(u, 3) * v) % n q = Point(pow(u, 3, n), pow(v, 3, n)) for p in sieve(b1): q = mul(pow(p, ilog(b1, p), n), q, an, ad, n) g = gcd(q.z, n) if 1 < g < n: return 1, g c = [Point(0, 0)] * (m + 1) b = [Point(0, 0)] * (m + 1) c[1] = double(q, an, ad, n) c[2] = double(c[1], an, ad, n) for i in xrange(1, m + 1): if i > 2: c[i] = add(c[i - 1], c[1], c[i - 2], n) b[i] = (c[i].x * c[i].z) % n g = 1 t = mul(b1 - 1 - 2 * m, q, an, ad, n) r = mul(b1 - 1, q, an, ad, n) for i in xrange(b1 - 1, b2, 2 * m): a = (r.x * r.z) % n for p in primes(i + 2, i + 2 * m, m): d = (p - i) // 2 g = (g * (((r.x - c[d].x) * (r.z + c[d].z)) - a + b[d])) % n r, t = add(r, c[m], t, n), r g = gcd(g, n) if 1 < g < n: return 2, g return "factorization failed"
def generate_key_pair(size=512, number=2, rnd=random.SystemRandom, k=DEFAULT_ITERATION, primality_algorithm=None, strict_size=True, e=0x10001): primes = [] lbda = 1 bits = size // number + 1 n = 1 while len(primes) < number: if number - len(primes) == 1: bits = size - integer_bit_size(n) + 1 prime = get_prime(bits, rnd, k, algorithm=primality_algorithm) if prime in primes: continue if e is not None and fractions.gcd(e, lbda) != 1: continue if strict_size and number - len(primes) == 1 and integer_bit_size(n*prime) != size: continue primes.append(prime) n *= prime lbda *= prime - 1 if e is None: e = 0x10001 while e < lbda: if fractions.gcd(e, lbda) == 1: break e += 2 assert 3 <= e <= n-1 public = keys.RsaPublicKey(n, e) private = keys.MultiPrimeRsaPrivateKey(primes, e, blind=True, rnd=rnd) return public, private
def testCase(a, b, x, y): gcd1 = gcd(a, b) gcd2 = gcd(x, y) if gcd1 == gcd2: print("YES") else: print("NO")
def solveTwo(e1, e2): (c,a,m) = e1 (d,b,n) = e2 if solveOne(c,a,m) == None: return None if solveOne(d,b,n) == None: return None if c!=1: a = solveOne(c,a,m) m//= gcd(c,m) if d!=1: b = solveOne(d,b,n) n//= gcd(d,n) g = gcd(m, n) newM = m // g newN = n // g if (a%g) != (b%g): return None buf = a x1 = (a - buf) // g x2 = (b - buf) // g ans = (x1 * (newM * inv(newN, newM)) + x2 * (newM * inv(newM, newN)) ) % (newM * newN) return (ans*g) + buf
def rsa(p,q,k): t = time() # we start the clock here rngs = deque() # store the rngs for testing n = p*q phi = (p-1) * (q-1) e = (p-1) # this block of code choses e so that gcd(e,phi)=1 while ( gcd(e,phi) != 1): e = randint(2, phi-1) x_0 = (p-1) # this block of code choses x_0 so that gcd(x_0,phi)=1 while ( gcd(e,phi) != 1): x_0 = randint(2, phi-1) z=0 for a in range(k): # here we generate k values x_0 = pow(x_0,e,n) rngs.append(x_0%2) t=time()-t print('--------') print('{0} bits generated with RSA'.format(k)) print('Generating time: {0}'.format(t)) sarray = stest(rngs) sarray.insert(0,t) return sarray
def factor(n, b1, b2, m, s): u = (s*s - 5) % n v = (4 * s) % n an = (pow(v-u, 3) * (3*u + v)) % n ad = (4 * pow(u, 3) * v) % n q = pow(u, 3) % n, pow(v, 3) % n for p in sieve(b1): q = mul(pow(p, ilog(b1,p)), q, an, ad, n) g = gcd(q[1], n) if 1 < g < n: return 1, g c = [(0,0)] * (m+1) b = [(0,0)] * (m+1) c[1] = double(q, an, ad, n) c[2] = double(c[1], an, ad, n) for i in range(1, m+1): if i > 2: c[i] = add(c[i-1], c[1], c[i-2], n) b[i] = (c[i][0] * c[i][1]) % n g = 1 t = mul(b1 - 1 - 2*m, q, an, ad, n) r = mul(b1 - 1, q, an, ad, n) for i in range(b1-1, b2, 2*m): a = (r[0] * r[1]) % n for p in primes(i+2, i+2*m, m): d = (p - i) / 2 g = g * ( ( (r[0] - c[d][0]) * (r[1] + c[d][1]) ) - a + b[d]) % n r, t = add(r, c[m], t, n), r g = gcd(g, n) if 1 < g < n: return 2, g return "factorization failed"
def brent(n): if n % 2 == 0: return 2 y, c, m = randint(1, n-1), randint(1, n-1), randint(1, n-1) g, r, q = 1, 1, 1 while g == 1: x = y for i in range(r): y = ( (y * y) % n + c ) % n k = 0 while k < r and g == 1: ys = y for i in range(min(m, r-k)): y = ( (y * y) % n + c ) % n q = q * ( abs(x - y)) % n g = gcd(q, n) k = k + m r = r*2 if g == n: while True: ys = ((ys * ys) % n + c) % n g = gcd(abs(x - ys), n) if g > 1: break return int(g)
def rabin_miller_trial(num): """ Find factor based on the Rabin-Miller trial. :param num: a random "witness" of primality. :return: > 1 if composite, 1 if probably prime. """ num = pow(num, remainder, prime) # For first iteration, 1 or -1 remainder implies prime if num == 1 or num == prime - 1: return 1 else: gcd = fractions.gcd(num-1, prime) if gcd > 1: return gcd # For next iterations, -1 implies prime, 1 implies composite for _ in xrange(exponent): num = pow(num, 2, prime) if num == prime - 1: return 1 else: gcd = fractions.gcd(num-1, prime) if gcd > 1: return gcd # It is a composite, but could not find a factor return -1
def prb(N): if N % 2 == 0: return 2 (y, c, m) = (random.randint(1, N - 1), random.randint(1, N - 1), random.randint(1, N - 1)) (g, r, q) = (1, 1, 1) while g == 1: x = y for i in range(r): y = (y * y % N + c) % N k = 0 while k < r and g == 1: ys = y for i in range(min(m, r - k)): y = (y * y % N + c) % N q = q * abs(x - y) % N g = fractions.gcd(q, N) k = k + m r = r * 2 if g == N: while True: ys = (ys * ys % N + c) % N g = fractions.gcd(abs(x - ys), N) if g > 1: break return g
def findCoprime(m): p = (3 * m // 4) + 3 while gcd(p - 1, m) != 1: p = p * gcd(p - 1, m) return p - 1
def compute(): SIZE = 18 # possible[i] holds all the possible capacitance values of a series/parallel # capacitor network that uses exactly i capacitors of 60 uF each possible = [] all = set() # Union of every possible[i] # Note: Each fraction is represented as a pair (num, den), where den > 0 and gcd(num, den) = 1. # This approach is much faster than using the fractions.Fraction class. possible.append(set()) possible.append({(60, 1)}) all.update(possible[1]) for i in range(2, SIZE + 1): poss = set() for j in range(1, i // 2 + 1): for (n0, d0) in possible[j]: for (n1, d1) in possible[i - j]: pseudosum = n0 * d1 + n1 * d0 numerprod = n0 * n1 denomprod = d0 * d1 npgcd = fractions.gcd(pseudosum, numerprod) dpgcd = fractions.gcd(pseudosum, denomprod) poss.add((pseudosum // dpgcd, denomprod // dpgcd)) # Parallel poss.add((numerprod // npgcd, pseudosum // npgcd)) # Series possible.append(poss) all.update(poss) return str(len(all))
def brent(N): if N%2==0: return 2 y,c,m = random.randint(1, N-1),random.randint(1, N-1),random.randint(1, N-1) g,r,q = 1,1,1 while g==1: x = y for i in range(r): y = ((y*y)%N+c)%N k = 0 while (k<r and g==1): ys = y for i in range(min(m,r-k)): y = ((y*y)%N+c)%N q = q*(abs(x-y))%N g = gcd(q,N) k = k + m r = r*2 if g==N: while True: ys = ((ys*ys)%N+c)%N g = gcd(abs(x-ys),N) if g>1: break return g
def pollard_brent_find_factor(n, max_iter=None): """Perform Brent's variant of the Pollard rho factorisation algorithm to attempt to a non-trivial factor of the given number n. If max_iter > 0, return None if no factors were found within max_iter iterations. """ y, c, m = (random.randint(1, n - 1) for _ in range(3)) r, q, g = 1, 1, 1 i = 0 while g == 1: x = y for _ in range(r): y = pollard_brent_f(c, n, y) k = 0 while k < r and g == 1: ys = y for _ in range(min(m, r - k)): y = pollard_brent_f(c, n, y) q = (q * abs(x - y)) % n g = gcd(q, n) k += m r *= 2 if max_iter: i += 1 if (i == max_iter): return None if g == n: while True: ys = pollard_brent_f(c, n, ys) g = gcd(abs(x - ys), n) if g > 1: break return g
def next(a, b): a += b # +1 help = a # invertieren a = b b = help a += b # +1 return [a//fractions.gcd(a,b),b//fractions.gcd(a,b)] # kuerzen
def runTests(self): # Checking if inputs satisfy conditions if not self.isPrime() : #print "Error: N is not prime!" return False if gcd(self.N,self.p) != 1 : #print "Error: gcd(N,p) is not 1" return False if gcd(self.N,self.q)!=1 : #print "Error: gcd(N,q) is not 1" return False if self.q<=(6*self.d+1)*self.p: #print "Error: q is not > (6*d+1)*p" return False if not poly.isTernary(self.f,self.d+1,self.d): #print "Error: f does not belong to T(d+1,d)" return False if not poly.isTernary(self.g,self.d,self.d): #print "Error: g does not belong to T(d,d)" return False return True
def pe182(): """ Exact number of unconcealed messages: (1 + gcd(e-1, p-1)) * (1 + gcd(e-1, p-1)) (1009 - 1) * (3643 - 1) = 2^5 * 3^3 * 7 * 607 Then e = 6 * k + 1 or 5, e % 7 != 0 and e % 607 != 0 """ from fractions import gcd p, q = 1009, 3643 emin, edict = p * q, {} for k in xrange(611856): for e in (6 * k + 1, 6 * k + 5): if e % 7 and e % 607: u = (1 + gcd(e-1, p-1)) * (1 + gcd(e-1, q-1)) emin = min(emin, u) if u in edict: edict[u] += e else: edict[u] = e # answer: 399788195976 return edict[emin]
def is_prime(self, n): if n == 2: return True if n < 2: return False for a in range(2, self.isqrt(n) + 1): for b in range(2, n): t = a ** b if t == n: return False if t > n: break logn = math.log(n,2) logn2 = logn ** 2 for r in IT.count(3): if fractions.gcd(r, n) == 1 and self.ordr(r, n) >= logn2: break for a in range(2, r + 1): if 1 < fractions.gcd(a, n) < n: return False if n <= r: return True for a in range(1, int(math.sqrt(self.phi(r)) * logn)): if not self.testan(a, n, r): return False return True
def __init__(self, numerator = 1, denominator = 1): ''' >>> a = ratios.IntervalRatio(4,3) ''' self.unreduced_num = Decimal(numerator) self.unreduced_den = Decimal(denominator) GCD = fractions.gcd(numerator, denominator) self.numerator = Decimal(numerator/GCD) self.denominator = Decimal(denominator/GCD) self.decimal = self.numerator/self.denominator octaveless = denominator octaves = 0 while ((octaveless * 2) < numerator): octaveless = octaveless * 2 octaves += 1 octaveless_GCD = fractions.gcd(numerator, octaveless) self.octaveless_num = numerator/octaveless_GCD self.octaveless_den = octaveless/octaveless_GCD self.octaves = octaves self.octaveless_decimal = self.octaveless_num/self.octaveless_den self.ratio = str(self.numerator) + ":" + str(self.denominator) self.ratio_unreduced = str(self.unreduced_num) + ":" + str(self.unreduced_den) self.ratio_octaveless = str(self.octaveless_num) + ":" + str(self.octaveless_den)
def brent(N): """Fast finding of a single factor""" if N % 2 == 0: return 2 y, c, m = random.randint(1, N - 1), random.randint(1, N - 1), random.randint(1, N - 1) g, r, q = 1, 1, 1 while g == 1: x = y for i in xrange(r): y = ((y * y) % N + c) % N k = 0 while k < r and g == 1: ys = y for i in xrange(min(m, r - k)): y = ((y * y) % N + c) % N q = q * (abs(x - y)) % N g = gcd(q, N) k = k + m r *= 2 if g == N: while True: ys = ((ys * ys) % N + c) % N g = gcd(abs(x - ys), N) if g > 1: break return g
def makechunks(dat, chunksize=0): Ny, Nx = np.shape(dat) if chunksize==0: # get optimal number of slices if Nx%2==0: H = [] for k in xrange(2,50): H.append(gcd(Nx,Nx/k)) hslice = np.max(H) else: dat = np.hstack( (dat,np.ones((Ny,1))) ) Ny, Nx = np.shape(dat) H = [] for k in xrange(2,50): H.append(gcd(Nx,Nx/k)) hslice = np.max(H) # get windowed data Zt,ind = humutils.sliding_window(dat,(Ny,hslice)) else: if chunksize>np.shape(data_port)[1]: Zt,ind = humutils.sliding_window(dat,(Ny,chunksize)) else: print "Error: chunk size is larger than number of scan lines. Please choose smaller chunk size ... exiting" return Zt, ind
def solve_the_problem(): a, b, n = [int(x) for x in input().split(' ')] turn = 0 while True: remove_stones = 0 if turn == 0: remove_stones = gcd(a, n) else: remove_stones = gcd(b, n) n -= remove_stones if n < 0: if turn == 0: print(1) return else: print(0) return if turn == 0: turn = 1 else: turn = 0
def gcds(nums): if len(nums) <= 1: return 0 gcd = fractions.gcd(nums[0], nums[1]) for n in nums: gcd = fractions.gcd(n, gcd) return gcd
def getMaxEarnings(self, fishCost, moveCost): # load all the yields self.createAllYields() y = self.level['yields'] # maximum depth of movement (num moves) maxDepth = gamedef.TOTAL_TIME / fishCost # optimisation: use less memory by lowering time d = gcd(gamedef.TOTAL_TIME, gcd(moveCost, fishCost)) t = gamedef.TOTAL_TIME / d fishC = fishCost / d moveC = moveCost / d # this gcd thing is a bit pretentious, since the rest # of the code assumes fishC is 1. gcd should better # be fishCost... # array of best values values = [[0 for i in range(maxDepth + 1)] for j in range(len(y))] # and now let's calculate benefits for pos in range(len(y)): # first element for every yield will stay 0, # as it means we did not fish there nfish = len(y[pos]) - pos * moveC nfish = 0 if nfish < 0 else nfish for i in range(nfish): val = y[pos][i]['value'] if None != y[pos][i] else 0 values[pos][i+1] = values[pos][i] + val # perform a O(n*t*k^2) algorithm :( val, moves = opt(values, t, fishC, moveC) return val
def main(): gcdwarning = "You chose an alpha%s value with no inverse. This program cannot reverse the cipher." if len(sys.argv) < 3: print "Usage: python affine.py 'image' r-multiplier r-shift [g-m g-s b-m b-s]\n" print "If no g and b keys are given, the r key will apply to all three channels." print "Input the original key used to encrypt the image, not the inverse." return elif len(sys.argv) < 8: #Assume image, r key. if gcd(int(sys.argv[2]), 256) != 1: print gcdwarning % ('') return key = [(int(sys.argv[2]), int(sys.argv[3]))]*3 else: #assume image, rgb key. if gcd(int(sys.argv[2]), 256) != 1: print gcdwarning % (' R') return if gcd(int(sys.argv[4]), 256) != 1: print gcdwarning % (' G') return if gcd(int(sys.argv[6]), 256) != 1: print gcdwarning % (' B') return key = [(naive_inverse(int(sys.argv[2])), int(sys.argv[3])), (naive_inverse(int(sys.argv[4])), int(sys.argv[5])), (naive_inverse(int(sys.argv[6])), int(sys.argv[7]))] img = deaffine(sys.argv[1], key) img.show()
def coarse(hoc_filename,cube_length,save_filename): # INPUT: NEURON .hoc filename to import (str), voxel cube side length (fl/str for gcd), name of file to create for mesh output (str) # >> cube_length: 'gcd' (gcd of box dims) OR floating-point (must be common factor of all box dims) # This function reads in NEURON data and passes their info to # coarse_gen(), then associates the tets of the STEPS Tetmesh object returned # to the NEURON sections which exist inside of them. # Returns a tet_hoc dictionary -- tet_hoc[tet_index] = [encapsulated hoc section references] -- as well as the Tetmesh object ## GET HOC SECTION INFO ## h.load_file(hoc_filename) allp = [[],[],[]] for s in h.allsec(): for j in range(int(h.n3d())): allp[0].append(h.x3d(j)) allp[1].append(h.y3d(j)) allp[2].append(h.z3d(j)) maxl = [max(allp[0]),max(allp[1]),max(allp[2])] minl = [min(allp[0]),min(allp[1]),min(allp[2])] bdim = [ maxl[0] - minl[0], maxl[1] - minl[1], maxl[2] - minl[2] ] print "dims: ", bdim print "mins: ", minl ## CREATE COARSE MESH ## if (cube_length == 'gcd'): gcd = fractions.gcd(fractions.gcd(bdim[0],bdim[1]),fractions.gcd(bdim[2],bdim[1])) print "GCD: ", gcd cube_length = gcd sm = coarse_gen(cube_length,bdim,minl,save_filename) ## ASSOCIATE HOC SECTIONS WITH THEIR TETS ## tet_hoc = tet_associate(sm[0]) return tet_hoc, sm[0]
def generating_keys(prime1,prime2): fie_function = (prime1-1)*(prime2-1) print("Fie Function: ",format(fie_function)) N = prime1*prime2 print("N: ",format(N)) i =2 encryption_key=0 while i < fie_function and encryption_key ==0: if gcd(N,i) == 1 and gcd(fie_function,i) == 1: encryption_key=i i+=1 print("Encryption Key: ",format(encryption_key)) decryption_key = 0 i = 1 check = 'true' while check =='true': if (i*encryption_key)%fie_function ==1: decryption_key = i check = 'false' else: i+=1 print("Decryption Key: ",format(decryption_key)) return [fie_function,N,decryption_key,encryption_key]
from fractions import gcd a, b, c, d = map(int, input().split()) lcm = int(c * d / gcd(c, d)) A = a - 1 l_cd = A - A // c - A // d + A // lcm r_cd = b - b // c - b // d + b // lcm print(r_cd - l_cd)
from fractions import gcd with open('A.in', 'r') as fin: lines = fin.readlines() T = int(lines[0]) for i in range(1, T + 1): line = lines[i] bits = line.split() N = int(bits[0]) PD = int(bits[1]) PG = int(bits[2]) Dgcd = gcd(PD, 100) Ddenom = 100 / Dgcd if Ddenom > N: #print "Ddenom > N" print "Case #{0}: Broken".format(i) continue Ggcd = gcd(PG, 100) WD = PD / Dgcd D = 100 / Dgcd WG = PG / Ggcd G = 100 / Ggcd #print "D:", D, "WD:", WD, "G:", G, "WG:", WG if PD == 100 and PG == 100: print "Case #{0}: Possible".format(i) elif PD == 0 and PG == 0: print "Case #{0}: Possible".format(i) elif PG == 100 or PG == 0: print "Case #{0}: Broken".format(i)
def lcm(a, b): return a * b / gcd(a, b)
def modInverse(a, m): g = gcd(a, m) if (g != 1): return -1 else: return powerm(a, m - 2, m)
def gcd(a, b): if (a == 0): return b return gcd(b % a, a)
#!/usr/bin/python from fractions import gcd import time start = time.clock() bound = 120000 #generate list with radicals radicals = [1 for _ in xrange(bound + 1)] for i in xrange(2, bound + 1): if radicals[i] == 1: radicals[i] = i for j in xrange(i + i, bound + 1, i): radicals[j] *= i tot = 0 for a in xrange(1, bound / 2 + 1): for b in xrange(a + 1, bound - a, 2 - a % 2): c = a + b if radicals[a] * radicals[b] * radicals[c] < c: if gcd(a, b) == 1: tot += c print a print tot print time.clock() - start
from fractions import gcd, Fraction m = Fraction(0, 1) for i in range(2, 1000001): if i % 7 == 0: continue numerator = (3 * i) / 7 if gcd(numerator, i) == 1 and Fraction(numerator, i) > m: m = Fraction(numerator, i) print m
def mgcd(*args): """Greatest common divisor that accepts multiple arguments.""" return mgcd(args[0], mgcd(*args[1:])) if len(args) > 2 else gcd(*args)
def result(n): lcm = 1 for i in range(1, n + 1): lcm = (lcm * i)/fractions.gcd(lcm, i) return int(lcm)
def GenVector(n): h = [] for i in range(n): if fc.gcd(i, n) == 1: h.append(i) return h
# -*- coding: utf-8 -*- """ Created on Sun May 22 15:51:04 2016 @author: qnl """ from __future__ import division import numpy as np import fractions count = 0 for i in xrange(4, 12001): start = np.floor(i / 3) + 1 end = np.ceil(i / 2) - 1 for j in xrange(int(start), int(end) + 1): if fractions.gcd(i, j) == 1: count += 1 print count
# encoding:utf-8 import copy import random import bisect #bisect_left これで二部探索の大小検索が行える import fractions #最小公倍数などはこっち import math import sys mod = 10**9+7 sys.setrecursionlimit(mod) # 再帰回数上限はでdefault1000 N = int(input()) dp = [[0,0] for i in range(N)] for i in range(N): a,b = map(int,input().split()) if i == 0: dp[0] = [a,b] else: dp[i][0] = max(fractions.gcd(dp[i-1][0],a),fractions.gcd(dp[i-1][1],a)) dp[i][1] = max(fractions.gcd(dp[i-1][0],b),fractions.gcd(dp[i-1][1],b)) print(max(dp[-1]))
def lcm(x, y): return (x * y) / gcd(x, y)
def lcm(a, b): """ Return the Least Common Multiple of a and b. """ return abs(a * b) / gcd(a, b) if a and b else 0
def lcm(a, b): return abs(a * b)/fractions.gcd(a, b) if a and b else 0 opt = TrainOptions().parse()
def lcm(a, b): return a // gcd(a, b) * b
def lcm(numbers): return reduce(lambda x, y: (x * y) / gcd(x, y), numbers, 1)
def lcm(n1, n2): """ Find least common multiple of two numbers """ return n1 * n2 / gcd(n1, n2)
def f(x): # sum of GCDs sum = 0 for i in range(1, x + 1): sum += gcd(i, x) return sum
4 6 8 Output: 24 48 72 96 120 #include<stdio.h> #include <stdlib.h> int main() { int a,b,c,i,f=0; scanf("%d%d%d",&a,&b,&c); for(i=1;i<1000;i++){ if(f==5) break; if(i%a==0&&i%b==0&&i%c==0){ printf("%d ",i); f++; } } } from fractions import gcd d=[int(input()),int(input()),int(input())] l=d[0] for i in d: l=l*i//gcd(l,i) i=1 while i!=6: print(l*i,end=" ") i+=1
import sys, fractions, math fin = open('B-small-attempt1.in', 'r') sys.stdout = open('B-small-attempt1.out', 'w') T = int(fin.readline()) for cs in range(1, T + 1): num = [int(x) for x in fin.readline().split(' ')] N = num[0] del num[0] if N == 2: a = math.fabs(num[0] - num[1]) if num[0] % a != 0: ans = a - num[0] % a else: ans = 0 else: a = math.fabs(num[0] - num[1]) b = math.fabs(num[1] - num[2]) c = math.fabs(num[2] - num[0]) gc = fractions.gcd(a, fractions.gcd(b, c)) if num[0] % gc != 0: ans = gc - num[0] % gc else: ans = 0 print('Case #%d: %d' % (cs, ans)) fin.close()
test_norm = (df_new_test - df_new_test.mean()) / (df_new_test.max() - df_new_test.min()) # In[ ]: train_norm.reset_index(inplace=True, drop=True) test_norm.reset_index(inplace=True, drop=True) # ### Making train and test sets with train_norm and test_norm # #### finding the gcf (greatest common factor) of train and test dataset's length and chop off the extra rows to make it divisible with the batchsize # In[89]: from fractions import gcd gcd(train_norm.shape[0], test_norm.shape[0]) # In[ ]: import math def roundup(x): return int(math.ceil(x / 100.0)) * 100 # In[ ]: train_lim = roundup(train_norm.shape[0]) test_lim = roundup(test_norm.shape[0])
import fractions for t in xrange(input()): a, b, c, d = map(int, raw_input().split()) g = fractions.gcd(c, d) diff = abs(a - b) i = (diff / g) * g j = i + g print min(abs(i - diff), j - diff)
#!/usr/bin/env python import fractions import math if __name__ == '__main__': T = int(raw_input()) for i in range(1, T + 1): P, Q = map(int, raw_input().split('/')) g = fractions.gcd(P, Q) P /= g Q /= g ans = 0 if Q != 0 and (Q & (Q - 1) == 0): if P == 1: ans = int(math.log(Q, 2)) else: while Q > P: Q /= 2 ans += 1 else: ans = 'impossible' print 'Case #%d: %s' % (i, ans)
import sys input = sys.stdin.readline from fractions import gcd Q = int(input()) Query = [] for _ in range(Q): a, b, q = map(int, input().split()) LR = [list(map(int, input().split())) for _ in range(q)] Query.append((a, b, q, LR)) def solve(lcm, m, x): cycle = x//lcm amari = x%lcm return (lcm-m)*cycle + max(0, amari-m+1) for a, b, q, LR in Query: lcm = a*b//gcd(a,b) m = max(a, b) ans = [] for l, r in LR: ans.append(solve(lcm, m, r)-solve(lcm, m, l-1)) print(*ans)
def lcm(x, y): # 最小公倍数 return (x * y) // fractions.gcd(x, y)
def smallest_r(n, log_2_n_squared, log_2_n): #find smallest r such that order_r(n) > log_2_n_squared #if f and n are not coprime, then SKIP this r. print "Running smallest_r(n , log_2_n_squared, log_2_n).." print "log_2_n is: " + str(log_2_n) print "log_2_n_squared is: " + str(log_2_n_squared) #intialise r r = 1 # G is the Multiplicative Group - (Z/rZ)* #Z_r - denotes set of integers modulo r #F_p denotes finite field with p elements #order_r(n) = order of n modulo r #integer n, positive integer r with gcd(n,r)=1, #multiplicative order of n modulo r is the smallest integer k with pow(n,k,r)=1 #r is unknown & we want to find. #print "pow(log_2_n, 5) is: "+str(pow(log_2_n,5)) #print "math.ceil(pow(log_2_n, 5)) is: "+str(math.ceil(pow(log_2_n,5))) #print "int(math.ceil(pow(log_2_n, 5))) is: "+str(int(math.ceil(pow(log_2_n,5)))) while r <= int(math.ceil(pow(log_2_n, 5))): #print "r is now: "+str(r) order_result = calc_order(n, r) #return status, order #status is False for "no exponent found" #status is True for exponent found status = order_result[0] #O(1) order_r_n = order_result[1] #O(1) #status = result[1] #print "status is: "+str(status) #raw_input("Waiting for user..") if status == False: #print "order_r_n is not found!" r = r + 1 elif status == True: if order_r_n <= log_2_n_squared: r = r + 1 elif order_r_n > log_2_n_squared: #check if r and n are coprime if gcd(r, n) <> 1: r = r + 1 else: print "r found: " + str(r) status = True return r, status else: print "order_r_n: " + str( order_r_n) + ", log_2_n_squared: " + str(log_2_n_squared) raw_input("Waiting for user..") else: print "order_r_n is: " + str(order_r_n) raw_input("Waiting for user..") if r == 1: status = False return r, status print "r not found!"
def lcm(a, b): return abs(a * b) / fractions.gcd(a, b) if a and b else 0
def _is_coprime(a, b): return gcd(a, b) == 1
from fractions import gcd A = ((1,1),(1,0)) def multi(a, b, k): return (((a[0][0]*b[0][0]+a[0][1]*b[1][0])%k, (a[0][0]*b[0][1]+a[0][1]*b[1][1])%k), ((a[1][0]*b[0][0]+a[1][1]*b[1][0])%k, (a[1][0]*b[0][1]+a[1][1]*b[1][1])%k)) def power(L, p, k): if p == 1: return L sq = power(L, p//2, k) if p%2==0: return multi(sq,sq,k) return multi(multi(sq,sq,k),L,k) n, m = map(int,input().split()) print(power(A,gcd(n,m),1000000007)[0][1])