Python math.gcd() Examples

The following are 30 code examples for showing how to use math.gcd(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module math , or try the search function .

Example 1
Project: pyleecan   Author: Eomys   File: comp_sym.py    License: Apache License 2.0 6 votes vote down vote up
def comp_sym(self):
    """Compute the symmetry factor of the machine

    Parameters
    ----------
    self : Machine
        A Machine object

    Returns
    -------
    sym : int
        Number of symmetries of the Machine
    is_antisym : bool
        True if an anti-symmetry is possible after the symmetries
    """

    sym_s, is_antisym_s = self.stator.comp_sym()
    sym_r, is_antisym_r = self.rotor.comp_sym()

    return gcd(sym_s, sym_r), is_antisym_s and is_antisym_r 
Example 2
Project: FATE   Author: FederatedAI   File: iterative_affine.py    License: Apache License 2.0 6 votes vote down vote up
def generate_keypair(key_size=1024, key_round=5, encode_precision=2 ** 100):
        key_size_array = np.linspace(start=int(key_size / 2), stop=key_size, num=key_round)
        key_size_array = np.floor(key_size_array).astype(np.int64)
        n_array = [0 for _ in range(key_round)]
        a_array = [0 for _ in range(key_round)]
        i = 0
        for key_size in key_size_array:
            n = random.SystemRandom().getrandbits(key_size)
            a = 0
            while True:
                a_ratio = random.SystemRandom().random()
                a_size = int(key_size * a_ratio)
                if a_size is 0:
                    continue
                a = random.SystemRandom().getrandbits(a_size)
                if math.gcd(n, a) == 1:
                    break
            n_array[i] = n
            a_array[i] = a
            i = i + 1
        return IterativeAffineCipherKey(a_array, n_array, encode_precision) 
Example 3
Project: Fluid-Designer   Author: Microvellum   File: test_fractions.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 4
Project: CatKit   Author: SUNCAT-Center   File: surface.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 5
Project: hackerrank   Author: rene-d   File: fibonacci-gcd.py    License: The Unlicense 6 votes vote down vote up
def power(M, k):
    """ fast exponentiation M^k """
    P = [1, 0,
         0, 1]

    if k == 0:
        return P
    if k == 1:
        return M

    while k != 0:
        if k % 2 == 1:
            P = multm(P, M)
        M = multm(M, M)
        k //= 2
    return P


# on utilise la propriété suivante:
# gcd(F(a), F(b)) = F(gcd(a, b))

# calcul du gcd(aᵢ) 
Example 6
Project: algorithms   Author: keon   File: find_primitive_root_simple.py    License: MIT License 6 votes vote down vote up
def find_primitive_root(n):
    if (n == 1):
        return [0]
        """ Exception Handeling :
        0 is the only primitive root of 1 """
    else:
        phi = euler_totient(n)
        p_root_list = []
        """ It will return every primitive roots of n. """
        for i in range (1, n):
            if (math.gcd(i, n) != 1):
                continue
                """ To have order, a and n must be
                relative prime with each other. """
            else:
                order = find_order(i, n)
                if (order == phi):
                    p_root_list.append(i)
                else:
                    continue
        return p_root_list 
Example 7
Project: algorithms   Author: keon   File: diffie_hellman_key_exchange.py    License: MIT License 6 votes vote down vote up
def find_primitive_root(n):
    if (n == 1):
        return [0]
        """ Exception Handeling :
        0 is the only primitive root of 1 """
    else:
        phi = euler_totient(n)
        p_root_list = []
        """ It will return every primitive roots of n. """
        for i in range (1, n):
            if (math.gcd(i, n) != 1):
                continue
                """ To have order, a and n must be
                relative prime with each other. """
            else:
                order = find_order(i, n)
                if (order == phi):
                    p_root_list.append(i)
                else:
                    continue
        return p_root_list 
Example 8
Project: Cirq   Author: quantumlib   File: shor.py    License: Apache License 2.0 6 votes vote down vote up
def naive_order_finder(x: int, n: int) -> Optional[int]:
    """Computes smallest positive r such that x**r mod n == 1.

    Args:
        x: integer whose order is to be computed, must be greater than one
           and belong to the multiplicative group of integers modulo n (which
           consists of positive integers relatively prime to n),
        n: modulus of the multiplicative group.

    Returns:
        Smallest positive integer r such that x**r == 1 mod n.
        Always succeeds (and hence never returns None).

    Raises:
        ValueError when x is 1 or not an element of the multiplicative
        group of integers modulo n.
    """
    if x < 2 or n <= x or math.gcd(x, n) > 1:
        raise ValueError(f'Invalid x={x} for modulus n={n}.')
    r, y = 1, x
    while y != 1:
        y = (x * y) % n
        r += 1
    return r 
Example 9
Project: audio   Author: pytorch   File: kaldi.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _lcm(a: int, b: int) -> int:
    return abs(a * b) // math.gcd(a, b) 
Example 10
Project: baseband   Author: mhvk   File: utils.py    License: GNU General Public License v3.0 5 votes vote down vote up
def lcm(a, b):
    """Calculate the least common multiple of a and b."""
    return abs(a * b) // gcd(a, b) 
Example 11
Project: hammer   Author: ucb-bar   File: __init__.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def gcd(*values: int) -> int:
    """
    Return the greatest common divisor of a series of ints

    :param values: The values of which to compute the GCD
    :return: The GCD
    """
    assert len(values) > 0
    # 3.5 moves fractions.gcd to math.gcd
    if sys.version_info.major == 3 and sys.version_info.minor < 5:
        import fractions
        return reduce(fractions.gcd, values)
    else:
        return reduce(math.gcd, values) 
Example 12
Project: hammer   Author: ucb-bar   File: __init__.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def lcm(*values: int) -> int:
    """
    Return the least common multiple of a series of ints

    :param values: The values of which to compute the LCM
    :return: The LCM
    """
    assert len(values) > 0
    # 3.5 moves fractions.gcd to math.gcd
    if sys.version_info.major == 3 and sys.version_info.minor < 5:
        import fractions
        return reduce(lambda x, y: (x * y) // fractions.gcd(x, y), values)
    else:
        return reduce(lambda x, y: (x * y) // math.gcd(x, y), values) 
Example 13
Project: segpy   Author: sixty-north   File: ibm_float.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def as_integer_ratio(self):
        sign = -1 if self.signbit else 1
        e16 = self.exp16
        if e16 >= 0:
            numerator = self.int_mantissa * EXPONENT_BASE**self.exp16
            denominator = _L24
        else:
            numerator = self.int_mantissa
            denominator = _L24 * EXPONENT_BASE**abs(self.exp16)
        divisor = gcd(numerator, denominator)
        reduced_numerator = sign * numerator // divisor
        reduced_denominator = denominator // divisor
        return reduced_numerator, reduced_denominator 
Example 14
Project: ivre   Author: cea-sec   File: target.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, target, rand=True, state=None):
        # see https://fr.wikipedia.org/wiki/Générateur_congruentiel_linéaire
        self.target = target
        self.nextcount = 0
        self.lcg_m = target.targetscount
        if state is not None:
            self.previous = state[0]
            self.lcg_c = state[1]
            self.lcg_a = state[2]
            self.nextcount = state[3]
        elif rand and target.targetscount > 1:
            # X_{-1}
            self.previous = random.randint(0, self.lcg_m - 1)
            # GCD(c, m) == 1
            self.lcg_c = random.randint(1, self.lcg_m - 1)
            # pylint: disable=deprecated-method
            while gcd(self.lcg_c, self.lcg_m) != 1:
                self.lcg_c = random.randint(1, self.lcg_m - 1)
            # a - 1 is divisible by all prime factors of m
            mfactors = reduce(mul, set(mathutils.factors(self.lcg_m)))
            # a - 1 is a multiple of 4 if m is a multiple of 4.
            if self.lcg_m % 4 == 0:
                mfactors *= 2
            self.lcg_a = mfactors + 1
        else:
            self.previous = self.lcg_m - 1
            self.lcg_a = 1
            self.lcg_c = 1 
Example 15
Project: PySyft   Author: OpenMined   File: rns_base.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, base):
        self.size = len(base)

        for i in range(self.size):
            if base[i] == 0:
                raise ValueError("rns_base is invalid")

            # The base must be coprime
            for j in base[:i]:
                if gcd(base[i], j) != 1:
                    raise ValueError("rns_base is invalid")

        self.base = base
        self.base_prod = None
        self.punctured_prod_list = [0] * self.size
        self.inv_punctured_prod_mod_base_list = [0] * self.size

        if self.size > 1:
            # Compute punctured product
            for i in range(self.size):
                self.punctured_prod_list[i] = multiply_many_except(self.base, self.size, i)

            # Compute the full product
            self.base_prod = self.punctured_prod_list[0] * self.base[0]

            # Compute inverses of punctured products mod primes
            for i in range(self.size):
                self.inv_punctured_prod_mod_base_list[i] = (
                    self.punctured_prod_list[i] % self.base[i]
                )
                self.inv_punctured_prod_mod_base_list[i] = invert_mod(
                    self.inv_punctured_prod_mod_base_list[i], self.base[i]
                )

        else:
            self.base_prod = self.base[0]
            self.punctured_prod_list[0] = 1
            self.inv_punctured_prod_mod_base_list[0] = 1 
Example 16
Project: minikerberos   Author: skelsec   File: encryption.py    License: MIT License 5 votes vote down vote up
def _nfold(str, nbytes):
	# Convert str to a string of length nbytes using the RFC 3961 nfold
	# operation.

	# Rotate the bytes in str to the right by nbits bits.
	def rotate_right(str, nbits):
		num = int.from_bytes(str, byteorder ='big', signed = False)
		size = len(str)*8
		nbits %= size
		body = num >> nbits
		remains = (num << (size - nbits)) - (body << size)
		return (body + remains).to_bytes(len(str), byteorder ='big', signed = False)

		

	# Add equal-length strings together with end-around carry.
	def add_ones_complement(str1, str2):
		n = len(str1)
		v = []
		for i in range(0,len(str1), 1):
			t = str1[i] + str2[i]
			v.append(t)
		
		#v = [ord(a) + ord(b) for a, b in zip(str1, str2)]
		# Propagate carry bits to the left until there aren't any left.
		while any(x & ~0xff for x in v):
			v = [(v[i-n+1]>>8) + (v[i]&0xff) for i in range(n)]
		return b''.join(x.to_bytes(1, byteorder = 'big', signed = False) for x in v)

	# Concatenate copies of str to produce the least common multiple
	# of len(str) and nbytes, rotating each copy of str to the right
	# by 13 bits times its list position.  Decompose the concatenation
	# into slices of length nbytes, and add them together as
	# big-endian ones' complement integers.
	slen = len(str)
	lcm = int(nbytes * slen / gcd(nbytes, slen))
	bigstr = b''.join((rotate_right(str, 13 * i) for i in range(int(lcm / slen))))
	slices = (bigstr[p:p+nbytes] for p in range(0, lcm, nbytes))
	
	return functools.reduce(add_ones_complement,  slices) 
Example 17
Project: vrequest   Author: cilame   File: pyprime.py    License: MIT License 5 votes vote down vote up
def prime_list_rho(n,root=None):
    # 之所以不用 def prime_list_rho(n,root=[]): 的方式是因为这里有坑
    # 作为函数对象的内部参数的临时地址多次使用会一直引用一个地址,
    # 所以考虑到该参数最后会作为结果返回出去,所以需要考虑初始化处理
    if root is None: root = []
    if not root and n<2:
        raise ValueError(n)
    if isprime_mr(n):
        root.append(n)
        return root
    from random import randint
    from math import gcd
    while True:
        x = randint(0,n-1) + 1
        c = randint(0,n-1) + 1
        y = x
        i = j = 2
        while True:
            x = ((x**2)+c)%n
            z = abs(x - y)
            d = gcd(z,n)
            if d>1 and d<n:
                prime_list_rho(d,root)
                prime_list_rho(n//d,root)
                return root
            if x == y: break
            if i == j:
                y = x
                j <<= 1
            i += 1

# 根据长度随机迭代,获取质数 
Example 18
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: collections.py    License: MIT License 5 votes vote down vote up
def _bcast_lwls(linewidths, dashes):
        """
        Internal helper function to broadcast + scale ls/lw

        In the collection drawing code, the linewidth and linestyle are cycled
        through as circular buffers (via ``v[i % len(v)]``).  Thus, if we are
        going to scale the dash pattern at set time (not draw time) we need to
        do the broadcasting now and expand both lists to be the same length.

        Parameters
        ----------
        linewidths : list
            line widths of collection
        dashes : list
            dash specification (offset, (dash pattern tuple))

        Returns
        -------
        linewidths, dashes : list
             Will be the same length, dashes are scaled by paired linewidth
        """
        if mpl.rcParams['_internal.classic_mode']:
            return linewidths, dashes
        # make sure they are the same length so we can zip them
        if len(dashes) != len(linewidths):
            l_dashes = len(dashes)
            l_lw = len(linewidths)
            gcd = math.gcd(l_dashes, l_lw)
            dashes = list(dashes) * (l_lw // gcd)
            linewidths = list(linewidths) * (l_dashes // gcd)

        # scale the dash patters
        dashes = [mlines._scale_dashes(o, d, lw)
                  for (o, d), lw in zip(dashes, linewidths)]

        return linewidths, dashes 
Example 19
Project: teleport   Author: tp4a   File: rsa.py    License: Apache License 2.0 5 votes vote down vote up
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 20
Project: teleport   Author: tp4a   File: rsa.py    License: Apache License 2.0 5 votes vote down vote up
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 21
Project: teleport   Author: tp4a   File: rsa.py    License: Apache License 2.0 5 votes vote down vote up
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
Project: Python   Author: TheAlgorithms   File: rsa_factorization.py    License: MIT License 5 votes vote down vote up
def rsafactor(d: int, e: int, N: int) -> List[int]:
    """
    This function returns the factors of N, where p*q=N
      Return: [p, q]

    We call N the RSA modulus, e the encryption exponent, and d the decryption exponent.
    The pair (N, e) is the public key. As its name suggests, it is public and is used to
        encrypt messages.
    The pair (N, d) is the secret key or private key and is known only to the recipient
        of encrypted messages.

    >>> rsafactor(3, 16971, 25777)
    [149, 173]
    >>> rsafactor(7331, 11, 27233)
    [113, 241]
    >>> rsafactor(4021, 13, 17711)
    [89, 199]
    """
    k = d * e - 1
    p = 0
    q = 0
    while p == 0:
        g = random.randint(2, N - 1)
        t = k
        while True:
            if t % 2 == 0:
                t = t // 2
                x = (g ** t) % N
                y = math.gcd(x - 1, N)
                if x > 1 and y > 1:
                    p = y
                    q = N // y
                    break  # find the correct factors
            else:
                break  # t is not divisible by 2, break and choose another g
    return sorted([p, q]) 
Example 23
Project: LeetCode-Python   Author: JiayangWu   File: 1447-最简分数.py    License: GNU General Public License v3.0 5 votes vote down vote up
def simplifiedFractions(self, n: int) -> List[str]:
        import math
        res = set()
        
        for down in range(1, n + 1):
            for up in range(1, down):
                if math.gcd(up, down) == 1:
                    res.add(str(up) + "/" + str(down))
                    
        return list(res) 
Example 24
Project: GraphicDesignPatternByPython   Author: Relph1119   File: collections.py    License: MIT License 5 votes vote down vote up
def _bcast_lwls(linewidths, dashes):
        '''Internal helper function to broadcast + scale ls/lw

        In the collection drawing code the linewidth and linestyle are
        cycled through as circular buffers (via v[i % len(v)]).  Thus,
        if we are going to scale the dash pattern at set time (not
        draw time) we need to do the broadcasting now and expand both
        lists to be the same length.

        Parameters
        ----------
        linewidths : list
            line widths of collection

        dashes : list
            dash specification (offset, (dash pattern tuple))

        Returns
        -------
        linewidths, dashes : list
             Will be the same length, dashes are scaled by paired linewidth

        '''
        if mpl.rcParams['_internal.classic_mode']:
            return linewidths, dashes
        # make sure they are the same length so we can zip them
        if len(dashes) != len(linewidths):
            l_dashes = len(dashes)
            l_lw = len(linewidths)
            gcd = math.gcd(l_dashes, l_lw)
            dashes = list(dashes) * (l_lw // gcd)
            linewidths = list(linewidths) * (l_dashes // gcd)

        # scale the dash patters
        dashes = [mlines._scale_dashes(o, d, lw)
                  for (o, d), lw in zip(dashes, linewidths)]

        return linewidths, dashes 
Example 25
Project: FATE   Author: FederatedAI   File: affine.py    License: Apache License 2.0 5 votes vote down vote up
def generate_keypair(key_size=2048, encode_precision=2 ** 100, a_ratio=None, b_ratio=None):
        n = random.SystemRandom().getrandbits(key_size)
        if a_ratio is None:
            a_ratio = random.SystemRandom().random()
        if b_ratio is None:
            b_ratio = random.SystemRandom().random()
        while True:
            a = random.SystemRandom().getrandbits(int(key_size * a_ratio))
            if math.gcd(n, a) == 1:
                break
        b = random.SystemRandom().getrandbits(max(1, int(key_size * b_ratio)))
        return AffineCipherKey(a, b, n, encode_precision) 
Example 26
Project: python3_ios   Author: holzschu   File: collections.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _bcast_lwls(linewidths, dashes):
        '''Internal helper function to broadcast + scale ls/lw

        In the collection drawing code the linewidth and linestyle are
        cycled through as circular buffers (via v[i % len(v)]).  Thus,
        if we are going to scale the dash pattern at set time (not
        draw time) we need to do the broadcasting now and expand both
        lists to be the same length.

        Parameters
        ----------
        linewidths : list
            line widths of collection

        dashes : list
            dash specification (offset, (dash pattern tuple))

        Returns
        -------
        linewidths, dashes : list
             Will be the same length, dashes are scaled by paired linewidth

        '''
        if mpl.rcParams['_internal.classic_mode']:
            return linewidths, dashes
        # make sure they are the same length so we can zip them
        if len(dashes) != len(linewidths):
            l_dashes = len(dashes)
            l_lw = len(linewidths)
            gcd = math.gcd(l_dashes, l_lw)
            dashes = list(dashes) * (l_lw // gcd)
            linewidths = list(linewidths) * (l_dashes // gcd)

        # scale the dash patters
        dashes = [mlines._scale_dashes(o, d, lw)
                  for (o, d), lw in zip(dashes, linewidths)]

        return linewidths, dashes 
Example 27
Project: scapy   Author: secdev   File: ipsec.py    License: GNU General Public License v2.0 5 votes vote down vote up
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
Project: claripy   Author: angr   File: strided_interval.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def complement(self):
        """
        Return the complement of the interval
        Refer section 3.1 augmented for managing strides

        :return:
        """
        # case 1
        if self.is_empty:
            return StridedInterval.top(self.bits)
        # case 2
        if self.is_top:
            return StridedInterval.empty(self.bits)
        # case 3
        y_plus_1 = StridedInterval._modular_add(self.upper_bound, 1, self.bits)
        x_minus_1 = StridedInterval._modular_sub(self.lower_bound, 1, self.bits)

        # the new stride has to be the GCD between the old stride and the distance
        # between the new lower bound and the new upper bound. This assure that in
        # the new interval the boundaries are valid solution when the SI is
        # evaluated.
        dist = StridedInterval._wrapped_cardinality(y_plus_1, x_minus_1, self.bits) - 1

        # the new SI is an integer
        if dist < 0:
            new_stride = 0
        elif self._stride == 0:
            new_stride = 1
        else:
            new_stride = math.gcd(self._stride, dist)
        return StridedInterval(lower_bound=y_plus_1,
                               upper_bound=x_minus_1,
                               bits=self.bits,
                               stride=new_stride,
                               uninitialized=self.uninitialized) 
Example 29
Project: claripy   Author: angr   File: strided_interval.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def lcm(a, b):
        """
        Get the least common multiple.

        :param a: The first operand (integer)
        :param b: The second operand (integer)
        :return: Their LCM
        """
        return a * b // math.gcd(a, b) 
Example 30
Project: claripy   Author: angr   File: strided_interval.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def gcd(a, b):
        """
        Get the greatest common divisor.

        :param a: The first operand (integer)
        :param b: The second operand (integer)
        :return: Their GCD
        """

        return math.gcd(a, b)