Java [Leetcode 204]Count Primes
题目描述:
Description:
Count the number of prime numbers less than a non-negative number, n.
解题思路:
Let's start with a isPrime function. To determine if a number is prime, we need to check if it is not divisible by any number less than n. The runtime complexity of isPrimefunction would be O(n) and hence counting the total prime numbers up to n would be O(n2). Could we do better?
As we know the number must not be divisible by any number > n / 2, we can immediately cut the total iterations half by dividing only up to n / 2. Could we still do better?
Let's write down all of 12's factors:
2 × 6 = 12
3 × 4 = 12
4 × 3 = 12
6 × 2 = 12As you can see, calculations of 4 × 3 and 6 × 2 are not necessary. Therefore, we only need to consider factors up to √n because, if n is divisible by some number p, then n= p × q and since p ≤ q, we could derive that p ≤ √n.
Our total runtime has now improved to O(n1.5), which is slightly better. Is there a faster approach?
The Sieve of Eratosthenes is one of the most efficient ways to find all prime numbers up to n. But don't let that name scare you, I promise that the concept is surprisingly simple.

Sieve of Eratosthenes: algorithm steps for primes below 121. "Sieve of Eratosthenes Animation" by SKopp is licensed under CC BY 2.0.We start off with a table of n numbers. Let's look at the first number, 2. We know all multiples of 2 must not be primes, so we mark them off as non-primes. Then we look at the next number, 3. Similarly, all multiples of 3 such as 3 × 2 = 6, 3 × 3 = 9, ... must not be primes, so we mark them off as well. Now we look at the next number, 4, which was already marked off. What does this tell you? Should you mark off all multiples of 4 as well?
4 is not a prime because it is divisible by 2, which means all multiples of 4 must also be divisible by 2 and were already marked off. So we can skip 4 immediately and go to the next number, 5. Now, all multiples of 5 such as 5 × 2 = 10, 5 × 3 = 15, 5 × 4 = 20, 5 × 5 = 25, ... can be marked off. There is a slight optimization here, we do not need to start from 5 × 2 = 10. Where should we start marking off?
In fact, we can mark off multiples of 5 starting at 5 × 5 = 25, because 5 × 2 = 10 was already marked off by multiple of 2, similarly 5 × 3 = 15 was already marked off by multiple of 3. Therefore, if the current number is p, we can always mark off multiples of p starting at p2, then in increments of p: p2 + p, p2 + 2p, ... Now what should be the terminating loop condition?
It is easy to say that the terminating loop condition is p < n, which is certainly correct but not efficient. Do you still remember Hint #3?
Yes, the terminating loop condition can be p < √n, as all non-primes ≥ √n must have already been marked off. When the loop terminates, all the numbers in the table that are non-marked are prime.
The Sieve of Eratosthenes uses an extra O(n) memory and its runtime complexity is O(n log log n). For the more mathematically inclined readers, you can read more about its algorithm complexity on Wikipedia.
代码如下:
public class Solution {
public int countPrimes(int n) {
boolean[] isPrime = new boolean[n];
int count = 0;
for(int i = 2; i < n; i++)
isPrime[i] = true;
for(int i = 2; i * i < n; i++){
if(!isPrime[i])
continue;
for(int j = i * i; j < n; j += i){
isPrime[j] = false;
}
}
for(int i = 2; i < n; i++){
if(isPrime[i])
count++;
}
return count;
}
}
Java [Leetcode 204]Count Primes的更多相关文章
- [leetcode] 204. Count Primes 统计小于非负整数n的素数的个数
题目大意 https://leetcode.com/problems/count-primes/description/ 204. Count Primes Count the number of p ...
- Java for LeetCode 204 Count Primes
Description: Count the number of prime numbers less than a non-negative number, n. 解题思路: 空间换时间,开一个空间 ...
- [LeetCode] 204. Count Primes 质数的个数
Count the number of prime numbers less than a non-negative number, n. Example: Input: 10 Output: 4 E ...
- [LeetCode] 204. Count Primes 计数质数
Description: Count the number of prime numbers less than a non-negative number, n click to show more ...
- LeetCode 204. Count Primes (质数的个数)
Description: Count the number of prime numbers less than a non-negative number, n. 题目标签:Hash Table 题 ...
- LeetCode 204 Count Primes
Problem: Count the number of prime numbers less than a non-negative number, n. Summary: 判断小于某非负数n的质数 ...
- (easy)LeetCode 204.Count Primes
Description: Count the number of prime numbers less than a non-negative number, n. Credits:Special t ...
- [LeetCode] 204. Count Primes 解题思路
Count the number of prime numbers less than a non-negative number, n. 问题:找出所有小于 n 的素数. 题目很简洁,但是算法实现的 ...
- LeetCode - 204. Count Primes - 埃拉托斯特尼筛法 95.12% - (C++) - Sieve of Eratosthenes
原题 原题链接 Description: Count the number of prime numbers less than a non-negative number, n. 计算小于非负数n的 ...
随机推荐
- java文件操作(输出目录、查看磁盘符)
问题描述: java操作文件,所有硬盘中所有文件路径 问题解决: (1)查看所有磁盘文件 注: 如上所示,使用接口 File.listRoots()可以返回所有磁盘文件,通过f ...
- ios开发之数据存取1-SQLite
iOS开发中常用的数据存取方式有: XML属性列表-PList NSKeyedArchiver 归档 Preference-偏好设置 SQLite3 Core Data-以面向对象的方式操作数据库SQ ...
- asp.net mvc4 使用KindEditor文本编辑器
最近做项目要用文本编辑器,编辑器好多种,这里介绍KindEditor在asp.net mvc4中的使用方法. 一.准备工作: 1.下载KindEditor.去官网:http://www.kindsof ...
- uva 11609
可以想到 答案为 1*C(1,n)+2*C(2,n)+3*C(3,n)+....+n*C(n,n); 由公式 k*C(k,n) = n*C(k-1,n-1) 所以最终答案 n*2^(n-1) 用到快速 ...
- 基于jQuery的TreeGrid组件详解
一.TreeGrid组件相关的类 1.TreeGrid(_config) _config:json格式的数据,组件所需要的数据都通过该参数提供. 2.TreeGridItem(_root, _rowI ...
- (int)、Convert.ToInt32()与int.Parse()的区别
1.(int)是类型转换,能够使用(int)进行强类型转换的只能是数值类型,如long.short.double等,这种转换时需要考虑精度问题. 如下的代码就行不通了: string text = & ...
- Const和ReadOnly区别及其用途--转载
常量的概念就是一个包含不能修改的值的变量,常量是C#与大多数编程语言共有的.但是,常量不必满足所有的要求.有时可能需要一些变量,其值不应改变,但在运行之前其值是未知的.C#为这种情形提供了另一个类型的 ...
- JS 变量或参数是否有值的判断
var node; …… 判断 node 是否有值,是否为 undefine,是否 null,直接使用两个!!,否定之否定: if (!!node){ .... }else{ .... } 这个条件判 ...
- POJ 1699 Best Sequence(DFS)
題目鏈接 題意 : 將幾個片段如圖所示方法縮成一個序列,求出最短這個序列. 思路 : 其實我也不知道怎麼做.....看網上都用了DP.....但是我不會.....這個DP不錯,還有用KMP+状压DP做 ...
- 用 Xamarin for VS 创建 aar 文件的绑定
预备工作:相关aar文件,Xamarin for VS一份.我这里以Android中挺火的 MaterialDesignLibrary 为例. 1.首先,创建一个Xamarin Binding Lib ...