204 count prime golang

  1. Count prime number

topic

Prime number less than the number of all non-negative integer n statistics.

Example:

输入: 10
输出: 4
解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。

My answer

This question is very easy to do it. Bool with a slice to record is not a prime number, then the number of true number again on the line, but on the border of two cycles worth more than think about it.
And is not a multiple prime number other than 1 itself.
Therefore, from the beginning with a 2 i, 2 of the multiples, the multiples of 3, 4, ... it is a multiple of a prime number non-labeled.
For example, find countPrimes (90):
When you have removed the multiple of 9, also need to consider multiple of 10 it?
Not necessary, because the front 10 and the numbers are multiplied, and then remove only multiple reject 10x10,10x11, but these are larger than 90. Thus the boundary where i is the i <sqrt (n), with i i <n-up would not import math.
Look at j, or consider countPrimes (90):
on your marks already finished multiples of 2, 3, and now i = 5, then 2x5,3x5,4x5 have been marked, so the lower bound is j = i j
i . In addition, as it is the mark of a multiple of i, so each incremental steps can step bigger, j = j + i.
I wondered if I had this very fine, but the general result like.
Here Insert Picture Description

func countPrimes(n int) int {
	if n<2{
		return 0
	}
	var isPrime []bool
	for i:=0;i<n;i++{
		isPrime=append(isPrime, true)
	}
	for i:=2;i*i<n;i++{
		for j:=i*i;j<n;j=j+i{
			isPrime[j]=false
		}
	}
	cnt:=0
	for _,v:=range isPrime{
		if v==true{
			cnt++
		}
	}
	return cnt-2
}
Published 38 original articles · won praise 0 · Views 1041

Guess you like

Origin blog.csdn.net/Cyan1956/article/details/104506042