当前位置: 首页>>代码示例>>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;未经允许,请勿转载。