Functions that answer questions
Read · 1 of 3
Return true or false
A function can return a bool, which makes code read like a sentence: if (isPrime(n)).
n is prime if nothing from 2 up to √n divides it. You only need to check up to √n: if n = a × b, one of a and b is at most √n. In code: loop while i * i <= n.
1bool isPrime(int n) {2 if (n < 2) return false;3 for (int i = 2; i * i <= n; i++) {4 if (n % i == 0) return false;5 }6 return true;7}