Exercises for Lesson 10
Exercise 1: A simple while loop
Write a function that uses a while
loop to calculate the sum of the first n
counting numbers: 1 + 2 + 3 + … + n
, given n
as a paramter.
def sumNumbers(n):
"""
Returns the sum of the counting numbers 1+2+...+n.
Returns 0 if the provided value of n is less than 1.
Assumes n is an integer.
"""
return 0 # replace with your code
Exercise 2: Dividing by 2
Write a function that takes a value n
and returns the number of times that n
can be divided by 2 (using integer division) before reaching 1. Your function should use a while
loop.
def numberTimesDivisible(n):
"""
Returns the number of times n can be divided by 2
(integer division) before reaching 1.
Assumes n is at least 1.
ex: n=1 -> 0
n=2 -> 1
n=3 -> 1
n=4 -> 2
"""
return -1 # replace with your code
Exercise 3: More practice
The greatest common divisor (GCD) of two values can be computed using Euclid’s algorithm. Starting with the values m
and n
, we repeatedly apply the formula: n, m = m, n % m
, until m
is 0. Then, n
is the GCD of the original values of m
and n
.
Write a function that finds the GCD of two numbers using this algorithm.
def gcd(m, n):
"""
Calculates the GCD of m and n using Euclid's algorithm.
Process:
* n = m
* m = n % m (note this must be simultaneous)
* continue until m is 0, then the result is in n
"""
return -1 # replace with your code