Python math.gcd() Examples

The following are 30 code examples of math.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 math , or try the search function .
Example #1
Source File: shor.py    From Cirq with 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 #2
Source File: test_fractions.py    From Fluid-Designer with 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 #3
Source File: fibonacci-gcd.py    From hackerrank with 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 #4
Source File: diffie_hellman_key_exchange.py    From algorithms with 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 #5
Source File: find_primitive_root_simple.py    From algorithms with 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 #6
Source File: comp_sym.py    From pyleecan with 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 #7
Source File: iterative_affine.py    From FATE with 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 #8
Source File: surface.py    From CatKit with 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 #9
Source File: test_gcd.py    From PyRival with Apache License 2.0 5 votes vote down vote up
def test_lcm():
    for _ in range(10000):
        x, y = random.randint(1, 1000), random.randint(1, 1000)
        assert lcm(x, y) == x * y // math.gcd(x, y) 
Example #10
Source File: euler108.py    From hackerrank with The Unlicense 5 votes vote down vote up
def pollard_brent(n):
    if n % 2 == 0: return 2
    if n % 3 == 0: return 3

    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 = (pow(y, 2, n) + c) % n

        k = 0
        while k < r and g == 1:
            ys = y
            for i in range(min(m, r - k)):
                y = (pow(y, 2, n) + c) % n
                q = q * abs(x-y) % n
            g = gcd(q, n)
            k += m
        r *= 2

    if g == n:
        while True:
            ys = (pow(ys, 2, n) + c) % n
            g = gcd(abs(x - ys), n)
            if g > 1: break

    return g 
Example #11
Source File: find_order_simple.py    From algorithms with MIT License 5 votes vote down vote up
def find_order(a, n):
    if ((a == 1) & (n == 1)):
        return 1
        """ Exception Handeling :
        1 is the order of of 1 """
    else:
        if (math.gcd(a, n) != 1):
            print ("a and n should be relative prime!")
            return -1
        else:
            for i in range(1, n):
                if (pow(a, i) % n == 1):
                    return i
            return -1 
Example #12
Source File: eigen_gate.py    From Cirq with Apache License 2.0 5 votes vote down vote up
def _lcm(vals: Iterable[int]) -> int:
    t = 1
    for r in vals:
        t = t * r // math.gcd(t, r)
    return t 
Example #13
Source File: shor.py    From Cirq with Apache License 2.0 5 votes vote down vote up
def find_factor(n: int,
                order_finder: Callable[[int, int], Optional[int]],
                max_attempts: int = 30) -> Optional[int]:
    """Returns a non-trivial factor of composite integer n.

    Args:
        n: integer to factorize,
        order_finder: function for finding the order of elements of the
            multiplicative group of integers modulo n,
        max_attempts: number of random x's to try, also an upper limit
            on the number of order_finder invocations.

    Returns:
        Non-trivial factor of n or None if no such factor was found.
        Factor k of n is trivial if it is 1 or n.
    """
    if sympy.isprime(n):
        return None
    if n % 2 == 0:
        return 2
    c = find_factor_of_prime_power(n)
    if c is not None:
        return c
    for _ in range(max_attempts):
        x = random.randint(2, n - 1)
        c = math.gcd(x, n)
        if 1 < c < n:
            return c  # coverage: ignore
        r = order_finder(x, n)
        if r is None:
            continue  # coverage: ignore
        if r % 2 != 0:
            continue  # coverage: ignore
        y = x**(r // 2) % n
        assert 1 < y < n
        c = math.gcd(y - 1, n)
        if 1 < c < n:
            return c
    return None  # coverage: ignore 
Example #14
Source File: shor.py    From Cirq with Apache License 2.0 5 votes vote down vote up
def quantum_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 or None if the
        algorithm failed. The algorithm fails when the result of the Quantum
        Phase Estimation is inaccurate, zero or a reducible fraction.

    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}.')

    circuit = make_order_finding_circuit(x, n)
    result = cirq.sample(circuit)
    eigenphase = read_eigenphase(result)
    f = fractions.Fraction.from_float(eigenphase).limit_denominator(n)
    if f.numerator == 0:
        return None  # coverage: ignore
    r = f.denominator
    if x**r % n != 1:
        return None  # coverage: ignore
    return r 
Example #15
Source File: rsa.py    From msldap with MIT License 5 votes vote down vote up
def GenerateKey(self,p = 0,q = 0,e = 0,d = 0,n = 0,l = 0):
		if p == 0:
			while True:
				p = self._random()
				if self._is_prime_number(p):break
		self._p = p

		if q == 0:
			while True:
				q = self._random()
				if self._is_prime_number(q) and p != q:break
		self._q = q

		if n == 0:
			n = p * q
		self._n = n

		if l == 0:
			l = self._lcm(p - 1, q  - 1)
		self._l = l

		if e == 0:
			while True:
				i = random.randint(2,l)
				if math.gcd(i, l) == 1:
				  e = i
				  break
		self._e = e

		if d == 0:
			_c, a, _b = self._etension_euclid(e, l)
			d = a % l
		self._d = d 
Example #16
Source File: rsa.py    From msldap with MIT License 5 votes vote down vote up
def _lcm(self,p,q):
		return (p * q) // math.gcd(p, q) 
Example #17
Source File: diffie_hellman_key_exchange.py    From algorithms with MIT License 5 votes vote down vote up
def find_order(a, n):
    if ((a == 1) & (n == 1)):
        return 1
        """ Exception Handeling :
        1 is the order of of 1 """
    else:
        if (math.gcd(a, n) != 1):
            print ("a and n should be relative prime!")
            return -1
        else:
            for i in range(1, n):
                if (pow(a, i) % n == 1):
                    return i
            return -1 
Example #18
Source File: find_primitive_root_simple.py    From algorithms with MIT License 5 votes vote down vote up
def find_order(a, n):
    if ((a == 1) & (n == 1)):
        return 1
        """ Exception Handeling :
        1 is the order of of 1 """
    else:
        if (math.gcd(a, n) != 1):
            print ("a and n should be relative prime!")
            return -1
        else:
            for i in range(1, n):
                if (pow(a, i) % n == 1):
                    return i
            return -1 
Example #19
Source File: sherlock-and-gcd.py    From hackerrank with The Unlicense 5 votes vote down vote up
def verif(a):
    d = a[0]
    for i in range(1, len(a)):
        d = gcd(d, a[i])

    if d == 1: return "YES"
    return "NO" 
Example #20
Source File: test_gcd.py    From PyRival with Apache License 2.0 5 votes vote down vote up
def test_extended_gcd():
    for _ in range(10000):
        x, y = random.randint(1, 1000), random.randint(1, 1000)
        g, s, r = extended_gcd(x, y)

        assert g == math.gcd(x, y)
        assert s * x + r * y == g 
Example #21
Source File: test_gcd.py    From PyRival with Apache License 2.0 5 votes vote down vote up
def test_gcd():
    for _ in range(10000):
        x, y = random.randint(1, 1000), random.randint(1, 1000)
        assert gcd(x, y) == math.gcd(x, y) 
Example #22
Source File: winfsp_runner.py    From parsec-cloud with GNU Affero General Public License v3.0 5 votes vote down vote up
def sorted_drive_letters(index: int, length: int, grouping: int = 5) -> str:
    """Sort the drive letters for a specific workspace index, by decreasing priority.

    The first letter should preferably be used. If it's not available, then the second
    letter should be used and so on.

    The number of workspaces (`length`) is also important as this algorithm will round
    it to the next multiple of 5 and use it to group the workspaces together.

    Example with 3 workspaces (rounded to 5 slots)

    | Candidates | W1 | W2 | W3 | XX | XX |
    |------------|----|----|----|----|----|
    | 0          | P  | Q  | R  | S  | T  |
    | 1          | U  | V  | W  | X  | Y  |
    | 2          | Z  | H  | I  | J  | K  |
    | 3          | L  | M  | N  | O  | P  |
    | 4          | Q  | R  | S  | T  | U  |
    | ...

    """
    assert 0 <= index < length
    # Round to the next multiple of grouping, i.e 5
    quotient, remainder = divmod(length, grouping)
    length = (quotient + bool(remainder)) * grouping
    # For the algorithm to work well, the lengths should be coprimes
    assert math.gcd(length, len(DRIVE_LETTERS)) == 1
    # Get all the letters by circling around the drive letter list
    result = ""
    for _ in DRIVE_LETTERS:
        result += DRIVE_LETTERS[index % len(DRIVE_LETTERS)]
        index += length
    return result 
Example #23
Source File: rsa.py    From learn_python3_spider with MIT License 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 #24
Source File: utilities.py    From CatKit with GNU General Public License v3.0 5 votes vote down vote up
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 #25
Source File: util.py    From AudioSegment with MIT License 5 votes vote down vote up
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 #26
Source File: util.py    From AudioSegment with MIT License 5 votes vote down vote up
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 #27
Source File: fractions.py    From Imogen with MIT License 5 votes vote down vote up
def gcd(a, b):
    """Calculate the Greatest Common Divisor of a and b.

    Unless b==0, the result will have the same sign as b (so that when
    b is divided by it, the result comes out positive).
    """
    import warnings
    warnings.warn('fractions.gcd() is deprecated. Use math.gcd() instead.',
                  DeprecationWarning, 2)
    if type(a) is int is type(b):
        if (b or a) < 0:
            return -math.gcd(a, b)
        return math.gcd(a, b)
    return _gcd(a, b) 
Example #28
Source File: kaldi.py    From audio with 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 #29
Source File: fractions.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def gcd(a, b):
    """Calculate the Greatest Common Divisor of a and b.

    Unless b==0, the result will have the same sign as b (so that when
    b is divided by it, the result comes out positive).
    """
    import warnings
    warnings.warn('fractions.gcd() is deprecated. Use math.gcd() instead.',
                  DeprecationWarning, 2)
    if type(a) is int is type(b):
        if (b or a) < 0:
            return -math.gcd(a, b)
        return math.gcd(a, b)
    return _gcd(a, b) 
Example #30
Source File: strided_interval.py    From claripy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def widen(self, b):
        ret = None

        if self.is_empty and not b.is_empty:
            ret = StridedInterval.top(bits=self.bits)

        elif self.is_empty:
            ret = b

        elif b.is_empty:
            ret = self

        else:
            new_stride = StridedInterval.gcd(self.stride, b.stride)
            l = StridedInterval.lower(self.bits, self.lower_bound, new_stride) if b.lower_bound < self.lower_bound else self.lower_bound
            u = StridedInterval.upper(self.bits, self.upper_bound, new_stride) if b.upper_bound > self.upper_bound else self.upper_bound
            if new_stride == 0:
                if self.is_integer and b.is_integer:
                    ret = StridedInterval(bits=self.bits, stride=1, lower_bound=l, upper_bound=u)
                else:
                    raise ClaripyOperationError('SI: operands are not reduced.')
            else:
                ret = StridedInterval(bits=self.bits, stride=new_stride, lower_bound=l, upper_bound=u)

        ret.normalize()
        return ret