Solutions (1.17 to 1.21)#

Solution to Exercise 1.17

Set n to 10
Set f to 1
Repeat until n equals 1:
    Set f to f times n
    Decrease n by 1
Print f

n = 10
f = 1
while n > 1:
    f = f * n
    n = n - 1 # or n -= 1
print(f)

Solution to Exercise 1.18

NB You should test your answer with a variety of values for a, b and c to check that it is working correctly. At least one test for each of the three type of solution.

a = 1
b = -1
c = -12

discriminant = b**2 - 4 * a * c

if discriminant > 0:
    print("The solutions are x =", (-b + discriminant**0.5)/(2*a), "and x =", (-b - discriminant**0.5)/(2*a))
elif discriminant == 0:
    print("The solution is x =", -b/(2*a))
else:
    print("There are no real solutions")

Solution to Exercise 1.19

Set value of n
Set value of m
Set i to 0
Repeat while n is greater than m:
    Subtract m from n
    Increase i by 1
Display i and n

n = 13
n_original = n
m = 3
i = 0
while n > m:
    n = n - m
    i += 1
print(n_original, "divided by", m, "equals", i, "remainder", n)

Solution to Exercise 1.20

It should be reasonably easy to follow the instructions in order to produce the correct code to perform the calculation. The only tricky part is to maintain the original value of t in a new variable t_orig so that we can include it in the final print statement.


t = 1000000
t_orig = t
s = t % 60
t = t // 60
m = t % 60
t = t // 60
h = t % 24
d = t // 24

print(t_orig, " seconds is ", d, " days ", h, ":", m, ":", s, sep="")

Solution to Exercise 1.21

1. The corrected psuedocode is shown below.

set value of n
set result to True
set i to 1 2 <- this number should be 2, not 1
repeat while i is less than n:
    if n is divisible by i
         set result to False
    increase i by 1 <- this line should be indented so that it is not part of the if block
display result

2.

n = 11 # pick any number
result = True
i = 2
while i < n:
    if n % i == 0:
        result = False
    i = i + 1
print(result)

3. This is tricky! One possible solution is shown below. We introduce two new variables: c which keeps a running total of the number of primes, and m which runs from 2 to n - 1. For each value, test if m is prime and if so increase c by one.

n = 7
c = 0 # new variable to count the number of primes
m = 2 # this variable replaces the previous variable n
while m < n:
    result = True
    i = 2
    while i < m:    
        if m % i == 0:
            result = False
        i = i + 1
    if result == True: # if n is prime, increase c by 1
        c = c + 1
    m = m + 1

print(c)