Advertisement
Smiechu

Odwrotność w grupie phi(n)

Nov 16th, 2022
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.74 KB | Software | 0 0
  1. def NWD(a,b):
  2.     temp = 0
  3.     while(a != b):
  4.         if(a == 1 or b == 1):
  5.             return 1
  6.         elif(a > b):
  7.             a = a - b
  8.         elif(a < b):
  9.             b = b - a
  10.  
  11.     if(a == b):
  12.         return a
  13.     elif(a > b):
  14.         return b
  15.     elif(b > a):
  16.         return a
  17.  
  18.  
  19. def phi(n):
  20.     numbers = []
  21.     for a in range(1,n):
  22.         if(NWD(a,n) == 1):
  23.             numbers.append(a)
  24.            
  25.     return numbers
  26.  
  27.  
  28. def inverse_elements_list(totients, n):
  29.     ie_list = []
  30.     for tot in totients:
  31.         for num in totients:
  32.             if(tot * num % n == 1):
  33.                 ie_list.append(num)
  34.  
  35.     return ie_list
  36.  
  37. def inv_elem(totients, n, a):
  38.     a_inv = 0
  39.     for tot in totients:
  40.         for num in totients:
  41.             if(tot * num % n == 1):
  42.                 if(tot == a):
  43.                     a_inv = num
  44.  
  45.     return a_inv
  46.  
  47. def GCD_modulo_extended(a,b):
  48.     x = 1
  49.     y = 0
  50.     remainder = 0
  51.     s = 1
  52.  
  53.     while(b != 0):
  54.         c = a % b
  55.         quotient = a // b
  56.         a = b
  57.         b = c
  58.  
  59.         remainder_prim = remainder
  60.         s_prim = s
  61.         remainder = x - quotient * remainder
  62.         s = y - quotient * s
  63.         x = remainder_prim
  64.         y = s_prim
  65.  
  66.     return (a, x, y)
  67.  
  68.  
  69. def main():
  70.     a = 47
  71.     n = 240
  72.     totients = phi(n)
  73.     inv_totients = inverse_elements_list(totients, n)
  74.     a_inv = inv_elem(totients, n, a)
  75.     gcd_E = GCD_modulo_extended(a, n)
  76.  
  77.     print(f"Totients phi({n}):\n {totients}\n")
  78.     print(f"Elementy odwrotne:\n {inv_totients}\n")
  79.     print(f"Element odwrotny do {a} to {a_inv}\n")
  80.     print(f"GCD_modulo_extended:\n {gcd_E}\n")
  81.     print(f"{a} * {a_inv} mod {n} = {(a*a_inv) % n}")
  82.  
  83. if __name__ == "__main__":
  84.     main()
  85.  
  86.  
  87.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement