-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
209 lines (171 loc) · 4.11 KB
/
main.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
package main
import (
"bufio"
"fmt"
"math"
"os"
"runtime"
"strconv"
"strings"
"sync"
"time"
)
func main() {
// Create a reader for standard input
reader := bufio.NewReader(os.Stdin)
// Prompt for input
fmt.Print("Enter the Range(int): ")
// Read input and trim spaces
input, err := reader.ReadString('\n')
if err != nil {
fmt.Println("Error reading input:", err)
return
}
input = strings.TrimSpace(input)
// Convert input to uint64
n, err := strconv.ParseUint(input, 10, 64)
if err != nil {
fmt.Println("Invalid input. Please enter a valid number.")
return
}
// Start timing
start := time.Now()
// Choose appropriate method based on input size
var primes []uint64
if n <= 10000000 { // 10^7
primes = SieveOfEratosthenes(n)
} else {
primes = Segmented_SOE(n)
}
// Calculate duration
duration := time.Since(start)
// Create filename with range
filename := fmt.Sprintf("primes_%d.csv", n)
// Create and write to file
file, err := os.Create(filename)
if err != nil {
fmt.Println("Error creating file:", err)
return
}
defer file.Close()
writer := bufio.NewWriter(file)
// Write each prime number to the file
for _, prime := range primes {
_, err := writer.WriteString(fmt.Sprintf("%d\n", prime))
if err != nil {
fmt.Println("Error writing to file:", err)
return
}
}
// Flush the writer to ensure all data is written
err = writer.Flush()
if err != nil {
fmt.Println("Error flushing writer:", err)
return
}
// Print execution time and success message
fmt.Println("Time taken:", duration)
fmt.Printf("File '%s' has been successfully created\n", filename)
}
// This is without segmenting.
func SieveOfEratosthenes(n uint64) []uint64 {
cores := runtime.NumCPU()
next := make(chan bool, cores)
var nums = make([]bool, n/2+1)
m := uint64(math.Sqrt(float64(n)))
for i := uint64(3); i <= m; i = i + 2 {
if nums[i/2] == false {
go goFill(nums, i, n, next)
next <- true
}
}
for i := 0; i < cores; i++ {
next <- true
}
var ps []uint64
if n >= 2 {
ps = append(ps, 2)
}
for i := uint64(3); i <= n; i = i + 2 {
if nums[i/2] == false {
ps = append(ps, i)
}
}
return ps
}
func fill(nums []bool, i uint64, max uint64) {
// a := 3 * i
iteration := 0
a := i * i
for a <= max {
iteration++
nums[a/2] = true
a = a + 2*i
}
}
func goFill(nums []bool, i uint64, max uint64, next chan bool) {
fill(nums, i, max)
<-next
}
// Segmented Sieve
var csegPool sync.Pool
func fillSegments(n uint64, basePrimes []uint64, allPrimes *[]uint64, segSize uint64, segNum uint64, next chan bool, nextTurn []chan bool) {
cseg := (csegPool.Get()).([]bool)
for i := uint64(0); i < segSize; i++ {
cseg[i] = false
}
segEnd := segSize * (segNum + 1)
for i := 0; i < len(basePrimes); i++ {
p := basePrimes[i]
pSquare := p * p
if pSquare > segEnd {
continue
}
jMax := segSize * (segNum + 1) / basePrimes[i]
startJ := basePrimes[i] - 1
if startJ < (segSize*segNum)/basePrimes[i] {
startJ = (segSize * segNum) / basePrimes[i]
}
for j := startJ; j < jMax; j++ {
sn := (j + 1) * basePrimes[i]
cseg[sn-segSize*segNum-1] = true
}
}
if segNum > 1 {
<-nextTurn[segNum]
}
for i := uint64(0); i < segSize; i++ {
if !cseg[i] && segSize*segNum+i+1 <= n {
*allPrimes = append(*allPrimes, segSize*segNum+i+1)
}
}
<-next
if int(segNum)+1 < len(nextTurn) {
nextTurn[segNum+1] <- true
}
csegPool.Put(cseg)
}
func Segmented_SOE(n uint64) (allPrimes []uint64) {
allPrimes = make([]uint64, 0, n/uint64(math.Log(float64(n))-1))
segSize := uint64(math.Sqrt(float64(n)))
csegPool.New = func() interface{} {
return make([]bool, segSize)
}
basePrimes := SieveOfEratosthenes(segSize)
allPrimes = append(allPrimes, basePrimes...)
cores := runtime.NumCPU()
next := make(chan bool, cores)
var nextTurn []chan bool
nextTurn = make([]chan bool, n/segSize+1)
for i := uint64(0); i < n/segSize+1; i++ {
nextTurn[i] = make(chan bool)
}
for segNum := uint64(1); segNum <= n/segSize-1; segNum++ {
go fillSegments(n, basePrimes, &allPrimes, segSize, segNum, next, nextTurn)
next <- true
}
for i := 0; i < cores; i++ {
next <- true
}
return allPrimes
}