204. Count Primes
Easy
Count the number of prime numbers less than a non-negative number, n.
Example:
Input: 10 Output: 4 Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
package leetcode.easy; public class CountPrimes { public int countPrimes(int n) { int count = 0; for (int i = 1; i < n; i++) { if (isPrime(i)) { count++; } } return count; } private static boolean isPrime(int number) { boolean flag = true; if (number < 2) { flag = false; } else if (number == 2) { flag = true; } else { for (int i = 2; i <= Math.sqrt(number); i++) { if (number % i == 0) { flag = false; break; } } } return flag; } @org.junit.Test public void test() { System.out.println(countPrimes(10)); } }