1.5. Further Practice#

Exercise 1.16

Recall the definition of factorial of a number \(n\),

\[n! = n \times (n-1) \times \ldots \times 2 \times 1.\]

We can calculate the factorial of \(n\) by repeated multiplation.

Write pseudocode for this computation then write Python code that calculates the factorial of any given number.

Exercise 1.17

Write a program which use the quadratic formula to print the solution to the quadratic equation \(ax^2 + bx + c = 0\), given variables a, b, and c. Your program should print:

The solutions are x = 4 and x = 1

or

The solution is x = 1

or

There are no real solutions

(Hint: first calculate the discriminant \(b^2-4ac\)).

Exercise 1.18

Given two integers \(n\) and \(m\) it is possible to perform division-with-remainder by repeatedly subtracting \(m\) from \(n\) until the result is less than \(m\). For example, to calculate 13 divided by 3:

13 - 3 = 10
10 - 3 = 7
7 - 3 = 4
4 - 3 = 1

13 divided by 3 equals 4 remainder 1.

  1. Write pseudocode for a program which performs this calulation.

  2. Turn your pseudocode into a Python program. The result of the calculation should be displayed in words as above.

(hint: you’ll need to create an extra variable to store the original value of n).

Exercise 1.19

A duration t in seconds can be converted to days, hours, minutes and seconds using integer division:

  1. Divide t by 60; set t to the quotient and call the remainder s.

  2. Divide t by 60; set t to the quotient and call the remainder m.

  3. Divide t by 24; set d to the quotient and call the remainder h.

Calculate the number of days, hours, minutes and seconds in one million seconds. Display the result as follows:

1000000 seconds is xx days H:M:S