Learnify Academy is a tuition centre in Bahrain. Classes are for students in Bahrain only.Tuition classes in Bahrain only

Algorithms · 3 marks

Write an algorithm prime(n) to check if n is prime.
(Hint: A prime number p has exactly two distinct factors, 1 and p. Can you make use of divisors(n) to write out prime(n)?)

Answer: prime(n): compute divisors(n); if the list has exactly two numbers, report “n is prime”, otherwise report “n is not prime”. E.g. divisors(13) = [1, 13] → prime; divisors(15) = [1, 3, 5, 15] → not prime.

Step-by-step solution

Idea: A prime has exactly two divisors, 1 and itself. The divisors algorithm already gives the full list of divisors, so we only need to count them.

  1. Algorithm prime(n)
    1. Let divisors-of-n be the list obtained by computing divisors(n).
    2. If divisors-of-n has exactly two elements, report “n is prime”.
    3. Otherwise, report “n is not prime”.1½ marks
  2. Why it is correct: every n ≥ 2 has at least the two divisors 1 and n. It is prime exactly when there are no others, that is, when the list has exactly two elements. For n = 1 the list is [1], one element, so 1 is correctly reported as not prime.1 mark
  3. Examples: divisors(13) = [1, 13], two elements → 13 is prime. divisors(15) = [1, 3, 5, 15], four elements → 15 is not prime.½ mark
  4. A quicker version: we can stop as soon as one divisor j with 2 ≤ j < n is found (then n is not prime), and by the pairs idea we only need to try j up to √n.
prime(n): compute divisors(n); report “prime” if the list has exactly two elements, and “not prime” otherwise.

Answer to write in the exam

Algorithm prime(n):

1. divisors-of-n = divisors(n)

2. If divisors-of-n has exactly 2 elements, report “n is prime”

3. Otherwise, report “n is not prime”

e.g. divisors(13) = [1, 13] → prime; divisors(15) = [1, 3, 5, 15] → not prime

∴ n is prime ⇔ divisors(n) has exactly two elements.

Common mistakes that cost marks

  • Testing “is 1 in the list and is n in the list”. That is true for every number, so it cannot detect primes.
  • Reporting 1 as prime. divisors(1) = [1] has only one element, so 1 is not prime.
  • Writing “if n has no factors, it is prime”; every number has the factors 1 and n.

How this can come in the exam

MCQ (1 mark)

prime(n) computes divisors(n). For n = 91, how many elements does this list have?

  1. 2
  2. 3
  3. 4
  4. 6
Show answer

(C) 4
91 = 7 × 13, so divisors(91) = [1, 7, 13, 91]: 4 elements, and 91 is not prime.

Try one yourself

Execute prime(n) for n = 29 and n = 51.

Show answer

divisors(29) = [1, 29], two elements: 29 is prime. divisors(51) = [1, 3, 17, 51], four elements: 51 is not prime.

More questions like this

All Algorithms questions · All maths questions