Arrays and strings · Exercise 4 of 100

Testing for Primes

A prime is a whole number greater than one whose only positive divisors are one and itself. To test a whole number greater than one, try dividing it by each whole number from two through its square root, stopping at the first exact division. If the number has a pair of factors greater than one, the smaller factor must be at or below the square root.

Try it yourself

You test 91 for primality by trying divisors in order, starting at 2. Which divisor first divides 91 exactly?

One-step hint

Use the last digit and digit sum of 91 to rule out easy divisors. Test the remaining candidates in order, watching for a zero remainder.

Worked solution
  1. The number 91 is odd, so 2, 4 and 6 cannot divide it. It falls between the multiples 90 and 93 of 3, and its last digit rules out 5.
  2. The next divisor is 7. Since 7 × 13 = 91, the division is exact and the test stops at 7.
DSA compiler