LeetCode_204. Count Primes

萝らか妹 提交于 2019-12-02 02:39:22

 

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));
	}
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!