Further Practice
1.5. Further Practice#
Exercise 1.16
Recall the definition of factorial of a number \(n\),
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.
Write pseudocode for a program which performs this calulation.
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:
Divide
t
by 60; sett
to the quotient and call the remainders
.Divide
t
by 60; sett
to the quotient and call the remainderm
.Divide
t
by 24; setd
to the quotient and call the remainderh
.
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