-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path204.计数质数.go
90 lines (78 loc) · 1.4 KB
/
204.计数质数.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
* @lc app=leetcode.cn id=204 lang=golang
*
* [204] 计数质数
*/
// @lc code=start
package main
import (
"fmt"
"math"
)
func countPrimes(n int) int {
mapA := map[int]int{3: 1, 5: 2, 7: 3, 8: 4}
isPrime := func(n int) bool {
limit := int(math.Sqrt(float64(n)))
for i := 2; i <= limit; i++ {
if n%i == 0 {
return false
}
}
return true
}
var result int
if v, ok := mapA[n-1]; ok {
result = v
} else {
result = countPrimes(n - 1)
}
if isPrime(n - 1) {
// fmt.Printf("%d is prime\n", n-1)
result += 1
}
return result
}
func countPrimes1(n int) int {
signs := make([]bool, n)
count := 0
res := []int{}
for i := 2; i < n; i++ {
// 如果 i是非质数则跳过
if signs[i] {
continue
}
count++ // 是质数
res = append(res, i) // 把质数都添加到result
// 倍数都不是质数
for j := i + i; j < n; j = j + i {
signs[j] = true
}
}
// fmt.Println(res)
return count
}
func countPrimes(n int) (cnt int) {
isPrime := make([]bool, n)
for i := range isPrime { // 默认都是质数
isPrime[i] = true
}
for i := 2; i < n; i++ {
if isPrime[i] {
cnt++
for j := 2 * i; j < n; j += i {
isPrime[j] = false
}
}
}
return
}
// @lc code=end
func main() {
var a int
a = 19
fmt.Printf("%d, %d\n", a, countPrimes1(a))
a = 5
fmt.Printf("%d, %d\n", a, countPrimes1(a))
a = 100000
fmt.Printf("%d, %d\n", a, countPrimes(a))
}