Beispiel #1
0
def generate_session_parameters():
    global sess_param_computed
    delta = 1
    alpha = 1
    beta = 1
    temp_q = 1

    for _ in range(m):
        p = sympy.sieve[random.randrange(psize)]
        pm.append(p)
        temp_q *= p

    for _ in range(n):
        p = sympy.sieve[random.randrange(psize)]
        while p in pm:
            p = sympy.sieve[random.randrange(psize)]
        pn.append(p)
        delta *= pow(p, 3)
        alpha *= pow(p, 2)*(p-1)
        beta *= p*(p-1)*temp_q

    y = random.randrange(delta)
    while sympy.igcd(y, delta) != 1:
        y = random.randrange(delta)

    sess_param_computed = True
    params["alpha"] = alpha
    params["delta"] = delta
    params["beta"] = beta
    params["totient_delta"] = totient(delta)
    params["y"] = y
Beispiel #2
0
def count_blinds_in_triangle(n):
    total = 0
    for level in range(2, ((n + 1) // 2) + 1):
        t = totient(level)
        total += t * (int(n / level) - 1)
        if level % 10000 == 0:
            print("%{:.2f}".format((level / n) * 100))
    return total
Beispiel #3
0
def range_totient(n: int, max_: int, min_: int = 2) -> int:
    """
    Calculate the count of numbers in an interval which are coprime to n
    """

    full_range = int(max_ - min_ - ((max_ - min_) % n))
    rt = int(round(totient(n) / n * full_range, 12))
    new_min = min_ + full_range + 1
    for i in range(new_min, max_ + 1):
        if are_coprime(i, n):
            rt += 1
    return rt
def matrix():
    determinant = []
    circulant_matrix = []
    eigenvalues=[]
    for i in range(2, 21):
        array = []
        for j in range(1, i + 1):
            l = totient(j)
            array.append(l)

        circulant_matrix.append(circulant(array))
        determinant.append(det(np.transpose(circulant_matrix[-1])))
        eigenvalues.append(eigvals(circulant_matrix[-1]))
    i = range(2, 21)
    df = DataFrame({'n': i, 'determininant': determinant, 'eigenvalues': eigenvalues})
    df.to_excel('rough.xlsx', index=False)
    for i in range(len(determinant)):
        print(np.transpose(circulant_matrix[i]))
        print("the eigenvalues of circulant matrix  for n= " + str(i + 2) + " is " + str(eigenvalues[i]))
        print("the determinant of circulant matrix  for n= " + str(i + 2) + " is " + str(determinant[i]))
        print()
Beispiel #5
0
def group_isomorphism(G, H, isomorphism=True):
    '''
    Compute an isomorphism between 2 given groups.

    Arguments:
        G (a finite `FpGroup` or a `PermutationGroup`) -- First group
        H (a finite `FpGroup` or a `PermutationGroup`) -- Second group
        isomorphism (boolean) -- This is used to avoid the computation of homomorphism
                                 when the user only wants to check if there exists
                                 an isomorphism between the groups.

    Returns:
    If isomorphism = False -- Returns a boolean.
    If isomorphism = True  -- Returns a boolean and an isomorphism between `G` and `H`.

    Summary:
    Uses the approach suggested by Robert Tarjan to compute the isomorphism between two groups.
    First, the generators of `G` are mapped to the elements of `H` and
    we check if the mapping induces an isomorphism.

    Examples
    ========

    >>> from sympy.combinatorics import Permutation
    >>> Permutation.print_cyclic = True
    >>> from sympy.combinatorics.perm_groups import PermutationGroup
    >>> from sympy.combinatorics.free_groups import free_group
    >>> from sympy.combinatorics.fp_groups import FpGroup
    >>> from sympy.combinatorics.homomorphisms import homomorphism, group_isomorphism
    >>> from sympy.combinatorics.named_groups import DihedralGroup, AlternatingGroup

    >>> D = DihedralGroup(8)
    >>> p = Permutation(0, 1, 2, 3, 4, 5, 6, 7)
    >>> P = PermutationGroup(p)
    >>> group_isomorphism(D, P)
    (False, None)

    >>> F, a, b = free_group("a, b")
    >>> G = FpGroup(F, [a**3, b**3, (a*b)**2])
    >>> H = AlternatingGroup(4)
    >>> (check, T) = group_isomorphism(G, H)
    >>> check
    True
    >>> T(b*a*b**-1*a**-1*b**-1)
    (0 2 3)

    '''
    if not isinstance(G, (PermutationGroup, FpGroup)):
        raise TypeError("The group must be a PermutationGroup or an FpGroup")
    if not isinstance(H, (PermutationGroup, FpGroup)):
        raise TypeError("The group must be a PermutationGroup or an FpGroup")

    if isinstance(G, FpGroup) and isinstance(H, FpGroup):
        G = simplify_presentation(G)
        H = simplify_presentation(H)
        # Two infinite FpGroups with the same generators are isomorphic
        # when the relators are same but are ordered differently.
        if G.generators == H.generators and (G.relators).sort() == (
                H.relators).sort():
            if not isomorphism:
                return True
            return (True, homomorphism(G, H, G.generators, H.generators))

    #  `_H` is the permutation group isomorphic to `H`.
    _H = H
    g_order = G.order()
    h_order = H.order()

    if g_order == S.Infinity:
        raise NotImplementedError(
            "Isomorphism methods are not implemented for infinite groups.")

    if isinstance(H, FpGroup):
        if h_order == S.Infinity:
            raise NotImplementedError(
                "Isomorphism methods are not implemented for infinite groups.")
        _H, h_isomorphism = H._to_perm_group()

    if (g_order != h_order) or (G.is_abelian != H.is_abelian):
        if not isomorphism:
            return False
        return (False, None)

    if not isomorphism:
        # Two groups of the same cyclic numbered order
        # are isomorphic to each other.
        n = g_order
        if (igcd(n, totient(n))) == 1:
            return True

    # Match the generators of `G` with subsets of `_H`
    gens = list(G.generators)
    for subset in itertools.permutations(_H, len(gens)):
        images = list(subset)
        images.extend([_H.identity] * (len(G.generators) - len(images)))
        _images = dict(zip(gens, images))
        if _check_homomorphism(G, _H, _images):
            if isinstance(H, FpGroup):
                images = h_isomorphism.invert(images)
            T = homomorphism(G, H, G.generators, images, check=False)
            if T.is_isomorphism():
                # It is a valid isomorphism
                if not isomorphism:
                    return True
                return (True, T)

    if not isomorphism:
        return False
    return (False, None)
import math
from math import gcd
from sympy.ntheory.factor_ import totient
from fractions import gcd
from functools import reduce
def f(n):
    return 27*(n**3)+9*(n**2)+3*n+1 #poly
n=1
l=[]
while n<250:
    l.append(totient(f(n)))
    n=n+1
print(reduce(gcd,l))
Beispiel #7
0
def modular_inverse(n: int, base: int) -> int:
    """Returns the modular inverse of n in base"""
    n **= totient(base) - 1
    n %= base
    return n
    p = sympy.sieve[random.randrange(psize)]
    while p in pm:
        p = sympy.sieve[random.randrange(psize)]
    pn.append(p)
    delta *= pow(p, 3)
    alpha *= pow(p, 2) * (p - 1)
    beta *= p * (p - 1) * temp_q

assert pow(beta, 2) % alpha == 0, 'alpha does not divide beta^2'
assert beta % alpha != 0, 'alpha divides beta'

print('beta % alpha', beta % alpha)

print("pn: {0}\npm: {1}\n".format(pn, pm))

totient_delta = totient(delta)
y = random.randrange(delta)

while sympy.igcd(y, delta) != 1:
    y = random.randrange(delta)

print("delta: {0}\n beta: {1}\n alpha: {2}\n y: {3}".format(
    delta, beta, alpha, y))

# Alice work (recebe delta, beta e alpha de trent)
xa = random.randrange(1, delta)
xb = random.randrange(1, totient_delta)
while xb * beta % totient_delta == 0:
    xb = random.randrange(totient_delta)
gamma = alpha * pow(xa, 2) + beta * xb
Beispiel #9
0
def totient(n: Union[int, float, complex]) -> int:
    try:
        import sympy.ntheory.factor_ as f_
    except ModuleNotFoundError:
        raise Exception("Install sympy to use number-theoretic functions!")
    return f_.totient(cint(n))
Beispiel #10
0
def egcd(a, b):
    x,y, u,v = 0,1, 1,0
    while a != 0:
        q, r = b//a, b%a
        m, n = x-u*q, y-v*q
        b,a, x,y, u,v = a,r, u,v, m,n
        gcd = b
    return gcd, x, y

if __name__ == '__main__':
    f = open("./bin/joan.marc.pastor_pubkeyRSA_pseudo.pem")
    key = RSA.import_key(f.read())
    f.close()

    n = key.n
    e = key.e

    # totient() implementation: https://docs.sympy.org/latest/_modules/sympy/ntheory/factor_.html#totient
    phiN = totient(n)
    gcd, a, b = egcd(e, phiN)
    if (a >= 0): 
        d = a
    else:
        d = a + phiN

    key = RSA.construct((n, e, d), consistency_check=False)
    f = open("./out/RSAprivateKey.pem", "wb")
    f.write(key.export_key("PEM"))
    f.close()
Beispiel #11
0
def group_isomorphism(G, H, isomorphism=True):
    '''
    Compute an isomorphism between 2 given groups.

    Arguments:
        G (a finite `FpGroup` or a `PermutationGroup`) -- First group
        H (a finite `FpGroup` or a `PermutationGroup`) -- Second group
        isomorphism (boolean) -- This is used to avoid the computation of homomorphism
                                 when the user only wants to check if there exists
                                 an isomorphism between the groups.

    Returns:
    If isomorphism = False -- Returns a boolean.
    If isomorphism = True  -- Returns a boolean and an isomorphism between `G` and `H`.

    Summary:
    Uses the approach suggested by Robert Tarjan to compute the isomorphism between two groups.
    First, the generators of `G` are mapped to the elements of `H` and
    we check if the mapping induces an isomorphism.

    Examples
    ========

    >>> from sympy.combinatorics import Permutation
    >>> from sympy.combinatorics.perm_groups import PermutationGroup
    >>> from sympy.combinatorics.free_groups import free_group
    >>> from sympy.combinatorics.fp_groups import FpGroup
    >>> from sympy.combinatorics.homomorphisms import homomorphism, group_isomorphism
    >>> from sympy.combinatorics.named_groups import DihedralGroup, AlternatingGroup

    >>> D = DihedralGroup(8)
    >>> p = Permutation(0, 1, 2, 3, 4, 5, 6, 7)
    >>> P = PermutationGroup(p)
    >>> group_isomorphism(D, P)
    (False, None)

    >>> F, a, b = free_group("a, b")
    >>> G = FpGroup(F, [a**3, b**3, (a*b)**2])
    >>> H = AlternatingGroup(4)
    >>> (check, T) = group_isomorphism(G, H)
    >>> check
    True
    >>> T(b*a*b**-1*a**-1*b**-1)
    (0 2 3)

    '''
    if not isinstance(G, (PermutationGroup, FpGroup)):
        raise TypeError("The group must be a PermutationGroup or an FpGroup")
    if not isinstance(H, (PermutationGroup, FpGroup)):
        raise TypeError("The group must be a PermutationGroup or an FpGroup")

    if isinstance(G, FpGroup) and isinstance(H, FpGroup):
        G = simplify_presentation(G)
        H = simplify_presentation(H)
        # Two infinite FpGroups with the same generators are isomorphic
        # when the relators are same but are ordered differently.
        if G.generators == H.generators and (G.relators).sort() == (H.relators).sort():
            if not isomorphism:
                return True
            return (True, homomorphism(G, H, G.generators, H.generators))

    #  `_H` is the permutation group isomorphic to `H`.
    _H = H
    g_order = G.order()
    h_order = H.order()

    if g_order == S.Infinity:
        raise NotImplementedError("Isomorphism methods are not implemented for infinite groups.")

    if isinstance(H, FpGroup):
        if h_order == S.Infinity:
            raise NotImplementedError("Isomorphism methods are not implemented for infinite groups.")
        _H, h_isomorphism = H._to_perm_group()

    if (g_order != h_order) or (G.is_abelian != H.is_abelian):
        if not isomorphism:
            return False
        return (False, None)

    if not isomorphism:
        # Two groups of the same cyclic numbered order
        # are isomorphic to each other.
        n = g_order
        if (igcd(n, totient(n))) == 1:
            return True

    # Match the generators of `G` with subsets of `_H`
    gens = list(G.generators)
    for subset in itertools.permutations(_H, len(gens)):
        images = list(subset)
        images.extend([_H.identity]*(len(G.generators)-len(images)))
        _images = dict(zip(gens,images))
        if _check_homomorphism(G, _H, _images):
            if isinstance(H, FpGroup):
                images = h_isomorphism.invert(images)
            T =  homomorphism(G, H, G.generators, images, check=False)
            if T.is_isomorphism():
                # It is a valid isomorphism
                if not isomorphism:
                    return True
                return (True, T)

    if not isomorphism:
        return False
    return (False, None)
from sympy.ntheory.factor_ import totient
p = 78203
q = 79999
print(totient(p * q))
Beispiel #13
0
	print("\n============\nSolution :\n============\n")

	data = np.array(data)

	print("M = product of all modulos =", " * ".join(map(str, data[:, 1])), "=", end = " ")
	M = np.prod(data[:, 1])
	print(M, '\n')

	M_arr = M//data[:, 1]
	print("Now, ")
	for i in range(len(M_arr)):
		print("M" + str(i+1), "=", "M/m" + str(i+1), "=", M_arr[i])
	print()

	inv_M = [pow(int(M_arr[i]), totient(data[i][1]) - 1, int(data[i][1])) for i in range(len(M_arr))]
	print("Now, ")
	for i in range(len(M_arr)):
		print("M" + str(i+1) + "^(-1) (mod m" + str(i+1) + ") =", inv_M[i])
	print()

	ans = 0
	print("Now, x = (Summation of all (ai)*(Mi)*(Mi^(-1)) (mod M), for all i = 1(1)n\n")
	print("So, x =", end = " ")

	for i in range(len(M_arr)):
		if i == len(M_arr)-1:
			print(str(data[i][0]) + "*" + str(M_arr[i]) + "*" + str(inv_M[i]), "(mod " + str(M) + ")")
		else:
			print(str(data[i][0]) + "*" + str(M_arr[i]) + "*" + str(inv_M[i]) + " +", end = " ")
		ans = (ans + (int(data[i][0]) * int(M_arr[i]) * int(inv_M[i])) % M) % M
Beispiel #14
0
def phi(n):
    return totient(n)
Beispiel #15
0
import math
from sympy.ntheory.factor_ import totient

if __name__ == '__main__':
	a, m = list(map(int, input("Enter number and modulo : ").split()))

	assert(math.gcd(a,m) == 1)

	phi = totient(m)

	for i in range(1, phi+1):
		if phi%i == 0:
			if pow(a,i,m) == 1:
				break

	print("\nORD(a) =", i, "(mod m)\n")
Beispiel #16
0
def len_of_chain(n):
    if n == 1:
        return 1
    return 1 + len_of_chain(totient(n))