Grade by Grade
B. Software Development · Software Development: Problem Solving, Design, Testing and the Life Cycle

Formulas in Algorithms: Hypotenuse, Primes, Area and Circumference

B3.2About 70 minutes
Learning goals
  • I can translate a mathematical formula into a correct Python expression, using brackets and the math module.
  • I can write functions for the hypotenuse of a right triangle and the area and circumference of a circle, and check them with known values.
  • I can design an efficient algorithm to decide whether a number is prime, and explain why checking divisors up to √n is enough.
  • I can use integer division and remainder (// and %) in algorithms such as time conversion and digit sums.

Words to know

formula
A rule written with symbols that calculates one quantity from others, such as A = πr².
hypotenuse
The longest side of a right triangle, opposite the right angle: c = √(a² + b²) (the Pythagorean theorem).
prime number
A whole number greater than 1 whose only positive divisors are 1 and itself. 2, 3, 5, 7 and 11 are prime; 1 is not.
trial division
Testing whether n is prime by dividing it by possible divisors and checking the remainder.
math module
Python's built-in library of maths tools: math.sqrt(), math.pi, math.hypot() and more. Load it with import math.
modulus (%)
The remainder after whole-number division. 17 % 5 is 2. n % d == 0 means d divides n exactly.
integer division (//)
Division that drops the remainder. 17 // 5 is 3.

Maths inside the machine

A lot of programming is turning a formula from a math or science class into code: the length of a ladder, the area of a rink, the cost of a loan, the speed of a puck. Computers are perfect at the arithmetic, but they only do exactly what you write. A missing bracket or a wrong order of operations gives a wrong answer with no error message.

This lesson works through the common problems named in the curriculum: the hypotenuse, prime numbers, and area and circumference. Along the way you will learn a reliable method for turning any formula into code.

Remember from math class

In Grade 8 and 9 math you used the Pythagorean theorem a² + b² = c², and formulas for the area A = πr² and circumference C = 2πr (or πd) of a circle. In Programming Basics you learned Python's arithmetic operators and the order of operations: brackets first, then *, /, //, %, then + and -.

A method for turning a formula into code

  1. Name the variables. Write down what each letter means and its units.
  2. Write the expression with brackets where the formula has grouping, fraction bars or roots. A fraction bar means "everything on top" ÷ "everything below", so it needs brackets: (a + b) / 2, not a + b / 2.
  3. Use the math module for π and roots: math.pi, math.sqrt().
  4. Wrap it in a function with parameters, so it is reusable and testable.
  5. Test with known values that you can check by hand, such as a 3-4-5 triangle.
walla = 6 mb = 1.5 mc = ?c² = a² + b²c = √(a² + b²)c = math.sqrt(a * a + b * b)c = √(36 + 2.25) ≈ 6.18 m
A ladder leaning against a wall forms a right triangle. The ladder is the hypotenuse c, so its length is √(a² + b²).
Worked example

Example 1: The hypotenuse

A ladder must reach 6 m up a wall, and its foot must be 1.5 m from the wall for safety. How long must the ladder be? Write a reusable function.

  1. Variables: legs a = 6 m and b = 1.5 m; hypotenuse c is the ladder.
  2. Formula: c = √(a² + b²). In Python: math.sqrt(a * a + b * b). (Python also has math.hypot(a, b), which does the same thing.)
  3. Test first with a known triangle: legs 3 and 4 must give 5.0. ✓
  4. Then the ladder: √(36 + 2.25) = √38.25 ≈ 6.18.

The ladder must be about 6.18 m long.

import math
def hypotenuse(a, b):
"""Return the hypotenuse of a right triangle with legs a and b."""
return math.sqrt(a * a + b * b)
print(hypotenuse(3, 4))
print(round(hypotenuse(6, 1.5), 2))

Output: 5.0 / 6.18 (one line each)

Area and circumference

For a circle of radius r: A = πr² and C = 2πr. In Python, r² is written r * r (or pow(r, 2)). Always state units: area is in square units.

import math
r = 2.5
area = math.pi * r * r
circumference = 2 * math.pi * r
print(f"Area: {area:.2f} m2")
print(f"Circumference: {circumference:.2f} m")

Output: Area: 19.63 m2 / Circumference: 15.71 m (one line each)

For a triangle when you know only the three sides, Heron's formula works: first find the semi-perimeter s = (a + b + c) ÷ 2, then area = √(s(s − a)(s − b)(s − c)). Notice the brackets around the whole sum before dividing by 2.

import math
def triangle_area(a, b, c):
"""Heron's formula: area from three side lengths."""
s = (a + b + c) / 2
return math.sqrt(s * (s - a) * (s - b) * (s - c))
print(f"{triangle_area(5, 6, 7):.2f}")

Output: 14.70. For sides 5, 6 and 7: s = 9 and the area is √(9 × 4 × 3 × 2) = √216 ≈ 14.70.

Prime numbers

A prime number is a whole number greater than 1 whose only divisors are 1 and itself. To test n, try dividing by possible divisors d. If n % d == 0 for any d between 2 and n − 1, then n is not prime.

But we can do far fewer divisions. Divisors come in pairs that multiply to n: for 36, the pairs are 1 × 36, 2 × 18, 3 × 12, 4 × 9 and 6 × 6. In every pair, one divisor is at most √n and the other is at least √n. So if n has no divisor from 2 up to √n, it has no divisor at all (other than 1 and itself).

1 × 362 × 183 × 124 × 96 × 6Short side: 1, 2, 3, 4, 6never more than √36 = 6.So test divisors 2 to 6;their partners come free.
Every rectangle with whole-number sides and area 36. Each one shows a divisor pair. The short side is always at most √36 = 6, so checking divisors up to 6 finds every pair.
Worked example

Example 2: An efficient prime test

Design and code a function is_prime(n). Then list the primes from 1 to 30.

  1. Extreme cases first: numbers less than 2 (including 0, 1 and negatives) are not prime. Return False straight away.
  2. Try divisors d = 2, 3, 4, ... while d × d ≤ n (that is, d ≤ √n, without needing a square root).
  3. If any d divides n exactly (n % d == 0), return False immediately.
  4. If the loop finishes without finding a divisor, return True.
  5. Test: 2 → loop does not run (2 × 2 > 2) → True ✓; 9 → d = 2 no, d = 3 yes → False ✓; 97 → tries 2 to 9, none divide → True ✓.

The function and the list of primes up to 30 are below.

def is_prime(n):
"""Return True if n is a prime number."""
if n < 2:
return False
d = 2
while d * d <= n:
if n % d == 0:
return False
d = d + 1
return True
primes = []
for n in range(1, 31):
if is_prime(n):
primes.append(n)
print(primes)

Output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

nDivisors checked by the slow design (2 to n − 1)Divisors checked by the √n design
97 (prime)958 (2 to 9)
10 007 (prime)10 00599 (2 to 100)
1 000 003 (prime)1 000 001999 (2 to 1000)
Why the √n design matters: the larger the number, the bigger the saving.

Integer division and remainder in algorithms

Two operators turn up again and again:

  • // (integer division) and % (remainder). n % 2 == 0 tests for even numbers; n % d == 0 tests for divisibility.
  • Converting units: 7384 seconds is 7384 // 3600 = 2 hours, then (7384 % 3600) // 60 = 3 minutes, and 7384 % 60 = 4 seconds.
  • Splitting digits: n % 10 is the last digit of n, and n // 10 removes it.
Just for fun

In 2024, a volunteer computing project announced a new largest known prime number. It has more than 41 million digits. Printing it would fill thousands of pages. Testing a number that size needs much cleverer maths than trying every n % d, plus a lot of computers.

Hands-on activity

Measure, then compute

You need: a tape measure or ruler, a round object (a plate, a pot lid or a hockey puck), and a computer with Python.

  1. Measure the diameter of the round object in centimetres. Write a program that asks for the diameter and prints the area and circumference (to 1 decimal place). Remember r = d ÷ 2.
  2. Check your circumference by wrapping a string around the object and measuring the string. How close is your program's answer?
  3. Measure the length and width of a rectangular table or book. Use your hypotenuse function to predict the length of its diagonal, then measure it.
  4. Use is_prime to find how many primes there are from 1 to 1000 (add a counter).

What to look for: measured and calculated values within a few millimetres; 168 primes from 1 to 1000.

Your turn

1

Translate into Python: the average of a and b is (a + b) ÷ 2. What goes wrong with a + b / 2?

2

Use the hypotenuse function to find the hypotenuse for legs 5 and 12, and for legs 8 and 15.

3

What does is_prime(91) return? Show the reasoning.

4

What does is_prime(97) return, and which divisors does it check?

5

Write a Python expression for the area of a circle with radius r and for its circumference.

6

A hockey puck has a diameter of about 7.6 cm. Find its circumference to one decimal place.

7

Convert 7384 seconds into hours, minutes and seconds using // and %.

More practice: warm-up

1

What is 17 % 5? What is 17 // 5?

2

Is 1 a prime number?

3

What must you write before you can use math.sqrt?

4

Write the Pythagorean theorem as a formula for c.

5

What does n % 2 == 0 test?

More practice: on your own

1

Find the area of a circle of radius 0.3 m to 3 decimal places, and the circumference of a circle of radius 6 cm to 2 decimal places.

2

A circular garden must have an area of 50 m². Rearrange A = πr² and find the radius to 2 decimal places. Write the Python expression.

3

Use Heron's formula to find the area of a triangle with sides 4, 5 and 8 (to 2 decimal places).

4

Trace this loop for n = 4721 and give the output: total = 0, while n > 0: total = total + n % 10 then n = n // 10; finally print(total).

5

Explain why is_prime loops while d * d <= n instead of while d <= n - 1. Is the answer ever different?

Challenge

1

Compound interest: A = P(1 + r)ⁿ. Write the Python expression and find A for P = $1000, r = 4% per year, n = 3 years (to the cent).

2

A student tested primes with while d * d < n: (less than, not less than or equal). Find an input where this gives the wrong answer, and explain.

3

Design an algorithm (pseudocode or Python) that finds the distance between two points (x1, y1) and (x2, y2) on a grid, and use it for (1, 2) and (7, 10).

Check your understanding

Quiz

1.

Which Python expression correctly finds the hypotenuse with legs a and b (after import math)?

2.

To test whether 101 is prime, the efficient algorithm tries divisors up to:

3.

What does (a + b) / 2 give for a = 7 and b = 4?

4.

Which formula gives the circumference of a circle with radius r?

5.

Which is the best way to check a hypotenuse function?

6.

What is 125 % 7?

7.

Why does is_prime return False immediately for n < 2?

For parents and teachers

Big idea: B3.2 asks students to solve common problems (hypotenuse, primes, area and circumference) by applying mathematical formulas in an algorithm. It connects directly to their math courses (MPM2D, and MCR3U or MCF3M this year).

How to help: Measure things together (a plate, a table diagonal) and compare the measurement with the program's answer. Ask "How do you know your program is right?" The answer should be "I tested it with values I can check by hand".

Common difficulties:

  • Missing brackets: a + b / 2 instead of (a + b) / 2, or math.sqrt(a) * a instead of math.sqrt(a * a + b * b).
  • Forgetting import math, or writing pi instead of math.pi.
  • Thinking 1 is prime, or stopping the prime loop one step too early (< instead of <=).
  • Forgetting square units for area.