當前位置: 首頁>>代碼示例>>Python>>正文


Python math.gcd方法代碼示例

本文整理匯總了Python中math.gcd方法的典型用法代碼示例。如果您正苦於以下問題:Python math.gcd方法的具體用法?Python math.gcd怎麽用?Python math.gcd使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在math的用法示例。


在下文中一共展示了math.gcd方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: comp_sym

# 需要導入模塊: import math [as 別名]
# 或者: from math import gcd [as 別名]
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 
開發者ID:Eomys,項目名稱:pyleecan,代碼行數:22,代碼來源:comp_sym.py

示例2: generate_keypair

# 需要導入模塊: import math [as 別名]
# 或者: from math import gcd [as 別名]
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) 
開發者ID:FederatedAI,項目名稱:FATE,代碼行數:23,代碼來源:iterative_affine.py

示例3: testMisc

# 需要導入模塊: import math [as 別名]
# 或者: from math import gcd [as 別名]
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)) 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:23,代碼來源:test_fractions.py

示例4: generate_indices

# 需要導入模塊: import math [as 別名]
# 或者: from math import gcd [as 別名]
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 
開發者ID:SUNCAT-Center,項目名稱:CatKit,代碼行數:26,代碼來源:surface.py

示例5: power

# 需要導入模塊: import math [as 別名]
# 或者: from math import gcd [as 別名]
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ᵢ) 
開發者ID:rene-d,項目名稱:hackerrank,代碼行數:24,代碼來源:fibonacci-gcd.py

示例6: find_primitive_root

# 需要導入模塊: import math [as 別名]
# 或者: from math import gcd [as 別名]
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 
開發者ID:keon,項目名稱:algorithms,代碼行數:23,代碼來源:find_primitive_root_simple.py

示例7: naive_order_finder

# 需要導入模塊: import math [as 別名]
# 或者: from math import gcd [as 別名]
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 
開發者ID:quantumlib,項目名稱:Cirq,代碼行數:26,代碼來源:shor.py

示例8: _lcm

# 需要導入模塊: import math [as 別名]
# 或者: from math import gcd [as 別名]
def _lcm(a: int, b: int) -> int:
    return abs(a * b) // math.gcd(a, b) 
開發者ID:pytorch,項目名稱:audio,代碼行數:4,代碼來源:kaldi.py

示例9: lcm

# 需要導入模塊: import math [as 別名]
# 或者: from math import gcd [as 別名]
def lcm(a, b):
    """Calculate the least common multiple of a and b."""
    return abs(a * b) // gcd(a, b) 
開發者ID:mhvk,項目名稱:baseband,代碼行數:5,代碼來源:utils.py

示例10: gcd

# 需要導入模塊: import math [as 別名]
# 或者: from math import gcd [as 別名]
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) 
開發者ID:ucb-bar,項目名稱:hammer,代碼行數:16,代碼來源:__init__.py

示例11: lcm

# 需要導入模塊: import math [as 別名]
# 或者: from math import gcd [as 別名]
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) 
開發者ID:ucb-bar,項目名稱:hammer,代碼行數:16,代碼來源:__init__.py

示例12: as_integer_ratio

# 需要導入模塊: import math [as 別名]
# 或者: from math import gcd [as 別名]
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 
開發者ID:sixty-north,項目名稱:segpy,代碼行數:15,代碼來源:ibm_float.py

示例13: __init__

# 需要導入模塊: import math [as 別名]
# 或者: from math import gcd [as 別名]
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 
開發者ID:cea-sec,項目名稱:ivre,代碼行數:30,代碼來源:target.py

示例14: __init__

# 需要導入模塊: import math [as 別名]
# 或者: from math import gcd [as 別名]
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 
開發者ID:OpenMined,項目名稱:PySyft,代碼行數:40,代碼來源:rns_base.py

示例15: _nfold

# 需要導入模塊: import math [as 別名]
# 或者: from math import gcd [as 別名]
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) 
開發者ID:skelsec,項目名稱:minikerberos,代碼行數:42,代碼來源:encryption.py


注:本文中的math.gcd方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。