Matthew L. Wright
Assistant Professor, St. Olaf College

Homework 20

CS 121 ⋅ Spring 2016

Upload your solutions to the following questions to Moodle for HW20. Type your answers to question 1 in a file, such as a text file or a Word document. For questions 2 and 3, please upload Python files.

  1. This question is about the Diffie-Hellman key exchange.

    Suppose that Alice and Bob want to establish a shared secret over the internet. They (publically) agree to use the prime p = 67 and generator g = 2.

    1. Alice chooses secret number a = 5. What does she send to Bob?
    2. Bob chooses secret number b = 42. What does he send to Alice?
    3. What is Alice and Bob's shared secret number?
  2. Recall that a prime number \(n\) is a positive integer that has no factors other than 1 and \(n\). Many encryption algorithms depend on prime numbers. Write a function that determines whether or not a number is prime. Your function header should be:

    def isPrime(n):

    For example, isPrime(7) returns True, while isPrime(9) returns False.

    Since 1 is not a prime number, make sure that isPrime(0) returns False!

    Hint: It suffices to test whether \(n\) is divisible by any integer between 2 and \(\sqrt{n}\). If no such integer divides \(n\), then \(n\) is prime. To do this, you probably want to use math.sqrt and math.floor (refer to the Python math documentation).

  3. Write the definition of a class called Robot that we will use as a simple model of a robot. Your class should meet the following specifications.

    Attributes: A Robot will have three attributes: a name, a build year, and a battery level.

    • name: a text string that gives the robot's name
    • build_year: a number; the year that the robot was built
    • battery_level: the current battery level, stored as a number between 0.0 (empty) and 1.0 (full)

    Methods: Implement the following methods in your Robot class:

    • Initializer: The initializer requires two arguments: a name and a build year, which are stored in the appropriate attribute variables. The battery level should be initialized to 0.
    • charge: requires no arguments, sets the battery level to 1.
    • introduce: requires no arguments, returns a string of the form "Hello, my name is ____.", where the robot puts its own name in the blank.
    • __str__: returns a string containing the robot's name, build year, and battery level.

    Sample use of a Robot:

    mike = Robot("Mike", 2016)
    print(mike.introduce()) #prints "Hello, my name is Mike."
    print(mike.battery_level) #prints 0
    print(mike.battery_level) #prints 1
    print(mike) #prints the name Mike, the year 2016, and the battery level 1