meta data for this page
Count Primes
Given an integer n
, return the number of prime numbers that are strictly less than n
.
Example 1:
Input: n = 10 Output: 4 Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
jump to: Search / User Tools / Main Content / Change Content Width
Software Quality Engineering & Beyond
You are here: SQE & Beyond » Interview Questions » Algorithm Interview Questions » Count Primes
Given an integer n
, return the number of prime numbers that are strictly less than n
.
Example 1:
Input: n = 10 Output: 4 Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
public int countPrimes(int n) { int count = 0; while (n-- > 0) { if (isPrime(n)) { count++; } } return count; } private static boolean isPrime(int n) { if (n <= 1) return false; for (int i = 2; i * i <= n; i++) { if (n % i == 0) { return false; } } return true; }