import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
Question 1. Write a function called sieve
that takes in a positive integer n
and returns a set
of the prime numbers less than or equal to n
. Use the Sieve of Eratosthenes to find the primes.
def sieve(n):
"""
Generate a set of prime numbers less than or equal to a positive integer.
"""
# BEGIN SOLUTION
is_prime = [True for _ in range(n + 1)]
p = 2
while p ** 2 <= n:
if is_prime[p]:
for i in range(p ** 2, n + 1, p):
is_prime[i] = False
p += 1
is_prime[0]= False
is_prime[1]= False
return set(i for i in range(n + 1) if is_prime[i])
# END SOLUTION
sieve(1) == set()
True
sieve(2) == {2}
True
sieve(3) == {2, 3}
True
# HIDDEN
sieve(20) == {2, 3, 5, 7, 11, 13, 17, 19}
True
""" # BEGIN TEST CONFIG
points: 1
hidden: true
""" # END TEST CONFIG
sieve(100) == {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97}
True
Question 2. Evaluate the integral:
$$ \int x e^x \, \mathrm dx $$SOLUTION:
$$ \begin{aligned} \int x e^x \, \mathrm dx &= x e^x - \int e^x \, \mathrm dx \\ &= x e^x - e^x + C \\ &= e^x (x - 1) + C \\ \end{aligned} $$Question 3. Graph the function $f(x) = \arctan \left ( e^x \right )$.
f = lambda x: np.arctan(np.exp(x))
xs = np.linspace(-10, 10, 100)
ys = f(xs)
plt.plot(xs, ys)
plt.xlabel("$x$")
plt.ylabel("$f(x)$")
plt.title(r"$f(x) = \arctan \left ( e^x \right )$");
Question 4. Write a function hailstone
that returns the hailstone sequence for a positive integer n
as a list
.
def hailstone(n):
"""
Generate the hailstone sequence of a positive integer.
"""
# BEGIN SOLUTION
if n == 1:
return [n]
elif n % 2 == 0:
return [n] + hailstone(n // 2)
else:
return [n] + hailstone(3 * n + 1)
# END SOLUTION
hailstone(1) == [1]
True
hailstone(2) == [2, 1]
True
hailstone(4) == [4, 2, 1]
True
""" # BEGIN TEST CONFIG
points: 1.5
hidden: true
""" # END TEST CONFIG
hailstone(20) == [20, 10, 5, 16, 8, 4, 2, 1]
True
""" # BEGIN TEST CONFIG
points: 1.5
hidden: true
""" # END TEST CONFIG
hailstone(9) == [9, 28, 14, 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
True
Question 5. Write a function gcd
that takes in two positive integers a
and b
and returns their greatest common divisor.
def gcd(a, b):
"""
Find the GCD of two positive integers.
"""
# BEGIN SOLUTION
if a == 0:
return b
return gcd(b % a, a)
# END SOLUTION
gcd(1, 1) == 1
True
gcd(2, 1) == 1
True
gcd(5, 5) == 5
True
gcd(10, 4) == 2
True
""" # BEGIN TEST CONFIG
points: 0.5
hidden: true
""" # END TEST CONFIG
gcd(121, 11) == 11
True
""" # BEGIN TEST CONFIG
points: 0.5
hidden: true
""" # END TEST CONFIG
gcd(807306, 622896) == 4098
True