C++20 sections · 1024 units
Open in Course

Problem: Is Prime

Checking divisibility

Write bool isPrime(int n) that returns true if prime, false otherwise. Loop from 2 to sqrt(n), check if n % i == 0. If yes, not prime. Finish the loop without finding a divisor, it is prime.

Handle edge cases first. If n < 2, return false immediately. Numbers 0 and 1 are not prime. 2 is prime. Test with 2, 3, 4, 5, 10, and 17. This is a helper function you will reuse. Filtering primes from a list? Call this for each one.

Write once, test thoroughly, then trust the name.