Python fractions.gcd() Examples
The following are 30
code examples of fractions.gcd().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
fractions
, or try the search function
.
Example #1
Source File: valid_layouts.py From mesh with Apache License 2.0 | 6 votes |
def _initialize_mtf_dimension_name_to_size_gcd(self, mtf_graph): """Initializer for self._mtf_dimension_name_to_size_gcd. Args: mtf_graph: an mtf.Graph. Returns: A {string: int}, mapping the name of an MTF dimension to the greatest common divisor of all the sizes it has. All these sizes being evenly divisible by some x is equivalent to the GCD being divisible by x. """ mtf_dimension_name_to_size_gcd = {} for mtf_operation in mtf_graph.operations: for mtf_tensor in mtf_operation.outputs: for mtf_dimension in mtf_tensor.shape.dims: mtf_dimension_name_to_size_gcd[mtf_dimension.name] = fractions.gcd( mtf_dimension_name_to_size_gcd.get(mtf_dimension.name, mtf_dimension.size), mtf_dimension.size) return mtf_dimension_name_to_size_gcd
Example #2
Source File: base_handler.py From pyspider with Apache License 2.0 | 6 votes |
def __new__(cls, name, bases, attrs): # A list of all functions which is marked as 'is_cronjob=True' cron_jobs = [] # The min_tick is the greatest common divisor(GCD) of the interval of cronjobs # this value would be queried by scheduler when the project initial loaded. # Scheudler may only send _on_cronjob task every min_tick seconds. It can reduce # the number of tasks sent from scheduler. min_tick = 0 for each in attrs.values(): if inspect.isfunction(each) and getattr(each, 'is_cronjob', False): cron_jobs.append(each) min_tick = fractions.gcd(min_tick, each.tick) newcls = type.__new__(cls, name, bases, attrs) newcls._cron_jobs = cron_jobs newcls._min_tick = min_tick return newcls
Example #3
Source File: Solution.py From leetcode-solutions with MIT License | 6 votes |
def rotate(self, nums, k): """ :type nums: List[int] :type k: int :rtype: None Do not return anything, modify nums in-place instead. """ import fractions if len(nums) == 0 or k == 0 or k == len(nums): return gcd = fractions.gcd(len(nums), k) for i in xrange(gcd): runner = i num = nums[runner] while True: next_idx = (runner + k) % len(nums) tmp = nums[next_idx] nums[next_idx] = num num = tmp runner = next_idx if runner == i: break
Example #4
Source File: addrspace.py From volatility with GNU General Public License v2.0 | 6 votes |
def calculate_alloc_stats(self): """Calculates the minimum_size and alignment_gcd to determine "virtual allocs" when read lengths of data It's particularly important to cast all numbers to ints, since they're used a lot and object take effort to reread. """ available_allocs = list(self.get_available_allocs()) self.minimum_size = int(min([size for _, size in available_allocs])) accumulator = self.minimum_size for start, _ in available_allocs: if accumulator is None and start > 1: accumulator = start if accumulator and start > 0: accumulator = fractions.gcd(accumulator, start) self.alignment_gcd = int(accumulator) # Pick an arbitrary cut-off that'll lead to too many reads if self.alignment_gcd < 0x4: debug.warning("Alignment of " + self.__class__.__name__ + " is too small, plugins will be extremely slow")
Example #5
Source File: addrspace.py From DAMM with GNU General Public License v2.0 | 6 votes |
def calculate_alloc_stats(self): """Calculates the minimum_size and alignment_gcd to determine "virtual allocs" when read lengths of data It's particularly important to cast all numbers to ints, since they're used a lot and object take effort to reread. """ available_allocs = list(self.get_available_allocs()) self.minimum_size = int(min([size for _, size in available_allocs])) accumulator = self.minimum_size for start, _ in available_allocs: if accumulator is None and start > 1: accumulator = start if accumulator and start > 0: accumulator = fractions.gcd(accumulator, start) self.alignment_gcd = int(accumulator) # Pick an arbitrary cut-off that'll lead to too many reads if self.alignment_gcd < 0x4: debug.warning("Alignment of " + self.__class__.__name__ + " is too small, plugins will be extremely slow")
Example #6
Source File: surface.py From CatKit with GNU General Public License v3.0 | 6 votes |
def generate_indices(max_index): """Return an array of miller indices enumerated up to values plus or minus some maximum. Filters out lists with greatest common divisors greater than one. Only positive values need to be considered for the first index. Parameters ---------- max_index : int Maximum number that will be considered for a given surface. Returns ------- unique_index : ndarray (n, 3) Unique miller indices """ grid = np.mgrid[max_index:-1:-1, max_index:-max_index-1:-1, max_index:-max_index-1:-1] index = grid.reshape(3, -1) gcd = utils.list_gcd(index) unique_index = index.T[np.where(gcd == 1)] return unique_index
Example #7
Source File: math.py From cyaron with GNU Lesser General Public License v3.0 | 6 votes |
def exgcd(a,b): """ Bézout coefficients (u,v) of (a,b) as: a*u + b*v = gcd(a,b) Result is the tuple: (u, v, gcd(a,b)). Examples: >>> exgcd(7*3, 15*3) (-2, 1, 3) >>> exgcd(24157817, 39088169) #sequential Fibonacci numbers (-14930352, 9227465, 1) Algorithm source: Pierre L. Douillet http://www.douillet.info/~douillet/working_papers/bezout/node2.html """ u, v, s, t = 1, 0, 0, 1 while b !=0: q, r = divmod(a,b) a, b = b, r u, s = s, u - q*s v, t = t, v - q*t return (u, v, a)
Example #8
Source File: addrspace.py From aumfor with GNU General Public License v3.0 | 6 votes |
def calculate_alloc_stats(self): """Calculates the minimum_size and alignment_gcd to determine "virtual allocs" when read lengths of data It's particularly important to cast all numbers to ints, since they're used a lot and object take effort to reread. """ available_allocs = list(self.get_available_allocs()) self.minimum_size = int(min([size for _, size in available_allocs])) accumulator = self.minimum_size for start, _ in available_allocs: if accumulator is None and start > 1: accumulator = start if accumulator and start > 0: accumulator = fractions.gcd(accumulator, start) self.alignment_gcd = int(accumulator) # Pick an arbitrary cut-off that'll lead to too many reads if self.alignment_gcd < 0x4: debug.warning("Alignment of " + self.__class__.__name__ + " is too small, plugins will be extremely slow")
Example #9
Source File: addrspace.py From vortessence with GNU General Public License v2.0 | 6 votes |
def calculate_alloc_stats(self): """Calculates the minimum_size and alignment_gcd to determine "virtual allocs" when read lengths of data It's particularly important to cast all numbers to ints, since they're used a lot and object take effort to reread. """ available_allocs = list(self.get_available_allocs()) self.minimum_size = int(min([size for _, size in available_allocs])) accumulator = self.minimum_size for start, _ in available_allocs: if accumulator is None and start > 1: accumulator = start if accumulator and start > 0: accumulator = fractions.gcd(accumulator, start) self.alignment_gcd = int(accumulator) # Pick an arbitrary cut-off that'll lead to too many reads if self.alignment_gcd < 0x4: debug.warning("Alignment of " + self.__class__.__name__ + " is too small, plugins will be extremely slow")
Example #10
Source File: test_fractions.py From Fluid-Designer with GNU General Public License v3.0 | 6 votes |
def testMisc(self): # fractions.gcd() is deprecated with self.assertWarnsRegex(DeprecationWarning, r'fractions\.gcd'): gcd(1, 1) with warnings.catch_warnings(): warnings.filterwarnings('ignore', r'fractions\.gcd', DeprecationWarning) self.assertEqual(0, gcd(0, 0)) self.assertEqual(1, gcd(1, 0)) self.assertEqual(-1, gcd(-1, 0)) self.assertEqual(1, gcd(0, 1)) self.assertEqual(-1, gcd(0, -1)) self.assertEqual(1, gcd(7, 1)) self.assertEqual(-1, gcd(7, -1)) self.assertEqual(1, gcd(-23, 15)) self.assertEqual(12, gcd(120, 84)) self.assertEqual(-12, gcd(84, -120)) self.assertEqual(gcd(120.0, 84), 12.0) self.assertEqual(gcd(120, 84.0), 12.0) self.assertEqual(gcd(F(120), F(84)), F(12)) self.assertEqual(gcd(F(120, 77), F(84, 55)), F(12, 385))
Example #11
Source File: test_fractions.py From gcblue with BSD 3-Clause "New" or "Revised" License | 5 votes |
def testMisc(self): self.assertEqual(0, gcd(0, 0)) self.assertEqual(1, gcd(1, 0)) self.assertEqual(-1, gcd(-1, 0)) self.assertEqual(1, gcd(0, 1)) self.assertEqual(-1, gcd(0, -1)) self.assertEqual(1, gcd(7, 1)) self.assertEqual(-1, gcd(7, -1)) self.assertEqual(1, gcd(-23, 15)) self.assertEqual(12, gcd(120, 84)) self.assertEqual(-12, gcd(84, -120))
Example #12
Source File: Utils.py From AdversarialAudioSeparation with MIT License | 5 votes |
def resample(audio, orig_sr, new_sr): orig_dtype = audio.dtype factor = gcd(orig_sr, new_sr) down = orig_sr / factor up = new_sr / factor audio = resample_poly(audio, up, down).astype(orig_dtype) return audio
Example #13
Source File: train.py From deep-learning-for-document-dewarping with MIT License | 5 votes |
def lcm(a,b): return abs(a * b)/fractions.gcd(a,b) if a and b else 0
Example #14
Source File: multirate.py From pyroomacoustics with MIT License | 5 votes |
def resample(x, p, q): import fractions gcd = fractions.gcd(p,q) p /= gcd q /= gcd m = np.maximum(p,q) h = low_pass(10*m+1, 1./(2.*m)) x_up = np.kron(x, np.concatenate(([1], np.zeros(p-1)))) from scipy.signal import fftconvolve x_rs = fftconvolve(x_up, h) x_ds = x_rs[h.shape[0]/2+1::q] x_ds = x_ds[:np.floor(x.shape[0]*p/q)] ''' import matplotlib.pyplot as plt plt.figure() plt.subplot(3,1,1) plt.plot(x) plt.subplot(3,1,2) plt.plot(x_rs) plt.subplot(3,1,3) plt.plot(x_ds) ''' return x_ds
Example #15
Source File: gcd_test.py From python-algorithms with Apache License 2.0 | 5 votes |
def test_gcd(self): self.assertEqual(fractions.gcd(30,50),GCD.greatest_common_divisor(30,50)) self.assertEqual(fractions.gcd(55555,123450),GCD.greatest_common_divisor(55555,123450)) self.assertEqual(fractions.gcd(-30,-50),GCD.greatest_common_divisor(-30,-50)) self.assertEqual(fractions.gcd(-1234,1234),GCD.greatest_common_divisor(-1234,1234))
Example #16
Source File: test_fractions.py From gcblue with BSD 3-Clause "New" or "Revised" License | 5 votes |
def __init__(self, num, den): g = gcd(num, den) self.num = num // g self.den = den // g
Example #17
Source File: example.py From python with MIT License | 5 votes |
def __init__(self, numer, denom): # abs used for backward compatibility with fractions.gcd gcd_num = abs(gcd(numer, denom)) self.numer = numer // gcd_num self.denom = denom // gcd_num if self.denom < 0: self.numer *= -1 self.denom *= -1
Example #18
Source File: example.py From python with MIT License | 5 votes |
def euclidian_coprimes(limit): mn = limit // 2 for n in range(1, int(ceil(sqrt(mn)))): if mn % n == 0: m = mn // n if (m - n) % 2 == 1 and gcd(m, n) == 1: yield m, n
Example #19
Source File: recipe-578797.py From code with MIT License | 5 votes |
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 = randprime(n) prime2 = randprime(n) composite = prime1 * prime2 totient = (prime1 - 1) * (prime2 - 1) if public is None: private = 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))
Example #20
Source File: equal_average_partition.py From InterviewBit with MIT License | 5 votes |
def avgset(self, A): s, n = sum(A), len(A) gcd = fractions.gcd(s, n) num = n // gcd self.A = sorted(A) for i in range(num, n // 2 + 1, num): k = self.knapsack(0, i, s * i // n) if k is not None: temp = k[:] return [k, [i for i in self.A if not i in temp or temp.remove(i)]] return [] # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
Example #21
Source File: rsa.py From learn_python3_spider with MIT License | 5 votes |
def rsa_recover_prime_factors(n, e, d): """ Compute factors p and q from the private exponent d. We assume that n has no more than two factors. This function is adapted from code in PyCrypto. """ # See 8.2.2(i) in Handbook of Applied Cryptography. ktot = d * e - 1 # The quantity d*e-1 is a multiple of phi(n), even, # and can be represented as t*2^s. t = ktot while t % 2 == 0: t = t // 2 # Cycle through all multiplicative inverses in Zn. # The algorithm is non-deterministic, but there is a 50% chance # any candidate a leads to successful factoring. # See "Digitalized Signatures and Public Key Functions as Intractable # as Factorization", M. Rabin, 1979 spotted = False a = 2 while not spotted and a < _MAX_RECOVERY_ATTEMPTS: k = t # Cycle through all values a^{t*2^i}=a^k while k < ktot: cand = pow(a, k, n) # Check if a^k is a non-trivial root of unity (mod n) if cand != 1 and cand != (n - 1) and pow(cand, 2, n) == 1: # We have found a number such that (cand-1)(cand+1)=0 (mod n). # Either of the terms divides n. p = gcd(cand + 1, n) spotted = True break k *= 2 # This value was not any good... let's try another! a += 2 if not spotted: raise ValueError("Unable to compute factors p and q from exponent d.") # Found ! q, r = divmod(n, p) assert r == 0 p, q = sorted((p, q), reverse=True) return (p, q)
Example #22
Source File: utilities.py From CatKit with GNU General Public License v3.0 | 5 votes |
def list_gcd(values): """Return the greatest common divisor of a list of values.""" if isinstance(values[0], float): values = np.array(values, dtype=int) gcd_func = np.frompyfunc(gcd, 2, 1) _gcd = np.ufunc.reduce(gcd_func, values) return _gcd
Example #23
Source File: util.py From AudioSegment with MIT License | 5 votes |
def lcm(a, b): """ Python 3.4 and others differ on how to get at the least common multiple. """ major, minor, _micro, _level, _serial = sys.version_info if major > 3 or minor > 4: return a * b // math.gcd(a, b) else: return a * b // fractions.gcd(a, b)
Example #24
Source File: util.py From AudioSegment with MIT License | 5 votes |
def lcm(a, b): """ Python 3.4 and others differ on how to get at the least common multiple. """ major, minor, _micro, _level, _serial = sys.version_info if major > 3 or minor > 4: return a * b // math.gcd(a, b) else: return a * b // fractions.gcd(a, b)
Example #25
Source File: test_fractions.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def __init__(self, num, den): g = math.gcd(num, den) self.num = num // g self.den = den // g
Example #26
Source File: disorderly_escape.py From foobar with MIT License | 5 votes |
def answer(w, h, s): grid=0 for cpw in cycle_partitions(w): for cph in cycle_partitions(h): m=cycle_count(cpw, w)*cycle_count(cph, h) grid+=m*(s**sum([sum([gcd(i, j) for i in cpw]) for j in cph])) return grid//(factorial(w)*factorial(h))
Example #27
Source File: ipsec.py From scapy with GNU General Public License v2.0 | 5 votes |
def _lcm(a, b): """ Least Common Multiple between 2 integers. """ if a == 0 or b == 0: return 0 else: return abs(a * b) // gcd(a, b)
Example #28
Source File: ipsec.py From smod-1 with GNU General Public License v2.0 | 5 votes |
def _lcm(a, b): """ Least Common Multiple between 2 integers. """ if a == 0 or b == 0: return 0 else: return abs(a * b) // fractions.gcd(a, b)
Example #29
Source File: Prelude.py From hask with BSD 2-Clause "Simplified" License | 5 votes |
def lcm(x, y): """ lcm :: Integral a => a -> a -> a lcm(x,y) is the smallest positive integer that both x and y divide. """ g = gcd(x, y) return 0 if g == 0 else (x * y) / g #=============================================================================# # Monads and functors
Example #30
Source File: Prelude.py From hask with BSD 2-Clause "Simplified" License | 5 votes |
def gcd(x, y): """ gcd :: Integral a => a -> a -> a gcd(x,y) is the non-negative factor of both x and y of which every common factor of x and y is also a factor; for example gcd(4,2) = 2, gcd(-4,6) = 2, gcd(0,4) = 4. gcd(0,0) = 0. (That is, the common divisor that is "greatest" in the divisibility preordering.) """ return fractions.gcd(x, y)