Question

You may import the following library functions in your module: from fractions import gcd from math...

You may import the following library functions in your module:

from fractions import gcd

from math import floor

from random import randint

You may also use:

• the built-in pow() function to compute modular exponents efficiently (i.e., ak mod n can be written in Python as pow(a,k,n)),

• the sum() function returns the sum of a list of integers (sum(1,2,3,4) returns 10).

problem 1

a. Implement a function invPrime(a, p) that takes two integers a and p > 1 where p is prime. The function should return the multiplicative inverse of a ∈ ℤ/pℤ (if a ≡ 0, it should return None). Your solution must use Fermat's little theorem.

>>> [invPrime(i, 7) for i in range(0,7)] [None, 1, 4, 5, 2, 3, 6]

>>> [invPrime(i, 13) for i in range(1,13)] [1, 7, 9, 10, 8, 11, 2, 5, 3, 4, 6, 12]

b. Include the following definition in your code. This non-recursive implementation of the extended Euclidean algorithm avoids a stack overflow error on large inputs.

def egcd(a, b):

(x, s, y, t) = (0, 1, 1, 0)

while b != 0:

k = a // b

(a, b) = (b, a % b)

(x, s, y, t) = (s - k*x, x, t - k*y, y)

return (s, t)

Given two inputs a and b, egcd(a, b) returns a solution (s, t) to the following instance of Bézout's identity: a ⋅ s + b ⋅ t = gcd(a,b)

Using egcd(), implement a function inv(a, m) that takes two integers a and m > 1. If a and m are coprime, it should return the multiplicative inverse of a ∈ ℤ/mℤ. If a and m are not coprime, it should return None.

>>> [inv(i, 13) for i in range(1,13)] [1, 7, 9, 10, 8, 11, 2, 5, 3, 4, 6, 12]

>>> [inv(i, 8) for i in range(1,8)] [1, None, 3, None, 5, None, 7]

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Code :-

  1. #initialiation as mentioned in the question
    from fractions import gcd
    from math import floor
    from random import randint

    #extended euclid without recursion
    def egcd (x1, x2) :
    res = []
    x, y, e1, e2 = 0, 1, 1, 0
    while x2 != 0 :
    const = x1//x2
    x1, x2 = x2, x1%x2
    x, y, e1, e2 = e1-const*x, e2-const*y, x, y
    res = [e1, e2]
    return res

    #inverse modular using egcd
    def inv (a, p) :
    if (gcd(a, p) != 1) :
    return None
    else :
    x, y = egcd(a, p)
    return (x%p+p)%p

    #inverse modular using fermat
    def invPrime(a, p) :
    if (gcd(a, p) != 1) :
    return None
    else :
    return pow(a, p-2, p)
      
    if __name__ == '__main__' :
    n = randint(5, 13)
    print ('fermat', n, [invPrime(i, n) for i in range(1, n)])
    print ('egcd', n, [inv(i, n) for i in range(1, n)])

Images :-

Note :-

  1. If you have any kind of doubt or confusion feel free to comment it down.
  2. If you like the answer please upvote it.
Add a comment
Know the answer?
Add Answer to:
You may import the following library functions in your module: from fractions import gcd from math...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • You may import the following library functions in your module: from fractions import gcd from math...

    You may import the following library functions in your module: from fractions import gcd from math import log from math import floor You may also use: • the .bit_length() method to efficiently obtain the bit length of an integer, • the abs() function for computing the absolute value of an integer, • and the // operator for integer division (you should avoid using / because it does not work for very large integers). Implement the following Python functions. These functions...

  • In this problem you will implement an algorithm for computing all the square roots of a congruenc...

    In this problem you will implement an algorithm for computing all the square roots of a congruence class in ℤ/nℤ, given a complete factorization of n into its distinct prime factor powers (assuming all the prime factors are in 3 + 4ℤ). a) Implement a Python function sqrtsPrime(a, p) that takes two arguments: an integer a and a prime number p. You may assume that a and p are coprime. If p is not in 3 + 4ℤ or a...

  • Implement the following Python functions. These functions take advantage of the generalized Euclid's lemma to make...

    Implement the following Python functions. These functions take advantage of the generalized Euclid's lemma to make it possible to generate a random number within a specified range. Your implementations must be extremely efficient, and must handle very large inputs, as shown in the examples below. Implementations that perform exhaustive, exponential-time searches will receive no credit. a. Implement a function closest(t, ks) that takes two arguments: a target integer t and a list of integers ks. The function should return the...

  • (+30) Provide a python program which will Populate an array(list) of size 25 with integers in...

    (+30) Provide a python program which will Populate an array(list) of size 25 with integers in the range -100 (negative 100)   to +100 inclusive Display the array and its length (use the len function) Display the average of all the integers in the array Display the number of even integers (how many) Display the number of odd integers (how many) Display the number of integers > 0   (how many) Display the number of integers < 0   (how many) Display the...

  • Write code for RSA encryption package rsa; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class RSA...

    Write code for RSA encryption package rsa; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class RSA {    private BigInteger phi; private BigInteger e; private BigInteger d; private BigInteger num; public static void main(String[] args) {    Scanner keyboard = new Scanner(System.in); System.out.println("Enter the message you would like to encode, using any ASCII characters: "); String input = keyboard.nextLine(); int[] ASCIIvalues = new int[input.length()]; for (int i = 0; i < input.length(); i++) { ASCIIvalues[i] = input.charAt(i); } String ASCIInumbers...

  • Please write functions to decrypt both the shift (Caesar) and linear ciphers. Also, answer the questions...

    Please write functions to decrypt both the shift (Caesar) and linear ciphers. Also, answer the questions in Python and show how it typed and ran inside the client. The def is what to start with 1) Write a function called decrypt that accepts three numbers (c, m, and k) and returns the corresponding plaintext (p) value as a number. You can assume the modulus (n) is 256. You will need to compute the multiplicative inverse of m mod 256 to...

  • Create a python add the following functions below to the module. Each section below is a...

    Create a python add the following functions below to the module. Each section below is a function that you must implement, make sure the function's names and parameters match the documentation (Copy-Paste). DO NOT put the functions in an if-name-main block. 1. def productSum(x: int, y: int, z: int) -> int This function should return: The product of x and y, if the product of x and y is less than z. Else it should return the sum of x...

  • Java help! Please help complete the min method below in bold. import java.util.Arrays; import java.util.ArrayList; import...

    Java help! Please help complete the min method below in bold. import java.util.Arrays; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * Provides an implementation of a binary search tree * with no balance constraints, implemented with linked nodes. * * * */ public class Bst<T extends Comparable<T>> implements Iterable<T> { ////////////////////////////////////////////////////////////////// // I M P L E M E N T T H E M I N M E T H O D B E L O W...

  • I need help with the following Java code Consider a class Fraction of fractions. Each fraction...

    I need help with the following Java code Consider a class Fraction of fractions. Each fraction is signed and has a numerator and a denominator that are integers. Your class should be able to add, subtract, multiply, and divide two fractions. These methods should have a fraction as a parameter and should return the result of the operation as a fraction. The class should also be able to find the reciprocal of a fraction, compare two fractions, decide whether two...

  • can you finish implementing the functions below ********************************************************************************************************** import urllib.request from typing import List, TextIO #...

    can you finish implementing the functions below ********************************************************************************************************** import urllib.request from typing import List, TextIO # Precondition for all functions in this module: Each line of the url # file contains the average monthly temperatures for a year (separated # by spaces) starting with January. The file must also have 3 header # lines. DATA_URL = 'http://robjhyndman.com/tsdldata/data/cryer2.dat' def open_temperature_file(url: str) -> TextIO: '''Open the specified url, read past the three-line header, and return the open file. ''' ... def avg_temp_march(f:...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT