当前位置:网站首页>Leetcode topic analysis count primes
Leetcode topic analysis count primes
2022-06-23 08:43:00 【ruochen】
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 _isPrime_function 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 = 12
As 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?
public int countPrimes(int n) {
int count = 0;
for (int i = 1; i < n; i++) {
if (isPrime(i)) count++;
}
return count;
}
private boolean isPrime(int num) {
if (num <= 1) return false;
// Loop's ending condition is i * i <= num instead of i <= sqrt(num)
// to avoid repeatedly calling an expensive function sqrt().
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) return false;
}
return true;
}- 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.
public int countPrimes(int n) {
boolean[] isPrime = new boolean[n];
for (int i = 2; i < n; i++) {
isPrime[i] = true;
}
// Loop's ending condition is i * i < n instead of i < sqrt(n)
// to avoid repeatedly calling an expensive function sqrt().
for (int i = 2; i * i < n; i++) {
if (!isPrime[i]) continue;
for (int j = i * i; j < n; j += i) {
isPrime[j] = false;
}
}
int count = 0;
for (int i = 2; i < n; i++) {
if (isPrime[i]) count++;
}
return count;
} public int countPrimes(int n) {
boolean[] b = new boolean[n];
// Mark non prime numbers as true
for (int i = 2; i * i < n; i++) {
if (b[i] == false) {
for (int j = i; i * j < n; j++) {
b[i * j] = true;
}
}
}
// count
int c = 0;
for (int i = 2; i < n; i++) {
if (b[i] == false) {
c++;
}
}
return c;
}边栏推荐
- Go data types (II) overview of data types supported by go and Boolean types
- Summary of Arthas vmtool command
- Interpretation of the most dirty technology in history, I can understand 60 it terms in seconds
- Multi-scale feature combination in target detection
- Qualcomm 9x07 two startup modes
- Arclayoutview: implementation of an arc layout
- Quickly create a consumer cluster
- 986. Interval List Intersections
- 5-旋转的小菊-旋转画布和定时器
- Spirit matrix for leetcode topic analysis
猜你喜欢

【云计算】GFS思想优势以及架构

为什么用生长型神经气体网络(GNG)?

PCB电路板特性检查项目都有哪些?

The rtsp/onvif protocol video platform easynvr startup service reports an error "service not found". How to solve it?

Monitor the cache update of Eureka client

论文阅读【Quo Vadis, Action Recognition? A New Model and the Kinetics Dataset】

Why use growth neural gas network (GNG)?

点云库pcl从入门到精通 第十章

Qualcomm 9x07 two startup modes

Data assets are king, analyzing the relationship between enterprise digital transformation and data asset management
随机推荐
[paper notes] catching both gray and black swans: open set supervised analog detection*
Open source technology exchange batch stream integrated data synchronization engine Chunjun data restore DDL function module analysis
Vulnhub | DC: 4 |【實戰】
Optimize your gradle module with a clean architecture
自组织映射神经网络(SOM)
Idea true permanent activation method and permanent activation code tutorial
4- draw ellipse, use timer
usb peripheral 驱动 - debug
The first day of employment more than ten years ago
vector的深度剖析及模拟实现
TDesign update weekly report (the first week of January 2022)
Basic use of check boxes and implementation of select all and invert selection functions
点云库pcl从入门到精通 第十章
How can I handle the "unable to load" exception when easyplayer plays webrtcs?
XSS via host header
Vulnhub | dc: 3 | [actual combat]
438. Find All Anagrams in a String
Arthas vmtool命令小结
5-rotating Daisy - rotating canvas and timer
测试-- 自动化测试selenium(关于API)