Skip to content

Commit 8950283

Browse files
Create Prime_Numbers.go
1 parent a649cdb commit 8950283

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed

Prime_Numbers.go

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"math"
6+
"os"
7+
"strconv"
8+
"github.com/douglasmakey/golang-algorithms-/utils"
9+
"time"
10+
)
11+
12+
// Define struct
13+
type numberResult struct {
14+
number int64
15+
isPrime bool
16+
}
17+
18+
// Define functions
19+
20+
// isPrime: validate N number is prime
21+
func isPrime(n int64) bool {
22+
var i, limit int64
23+
if n <= 1 {
24+
return false
25+
}
26+
27+
if n == 2 {
28+
return true
29+
}
30+
31+
if math.Mod(float64(n), 2) == 0 {
32+
return false
33+
}
34+
35+
36+
limit = int64(math.Ceil(math.Sqrt(float64(n))))
37+
for i = 3; i <= limit; i += 2 {
38+
if math.Mod(float64(n), float64(i)) == 0 {
39+
return false
40+
}
41+
}
42+
return true
43+
}
44+
45+
// createNrAndValidate: Receive number and validate if is prime, send channel this same
46+
func createNrAndValidate(n int64, c chan numberResult) {
47+
48+
result := new(numberResult)
49+
result.number = n
50+
result.isPrime = isPrime(n)
51+
c <- *result
52+
}
53+
54+
func initGoCalculations(min int64, max int64, c chan numberResult) {
55+
var i int64
56+
for i = min; i <= max; i++ {
57+
go createNrAndValidate(i, c)
58+
}
59+
}
60+
61+
func primesInRange(min int64, max int64) (primeArr []int64) {
62+
defer utils.TimeTrack(time.Now(), "primesInRange")
63+
64+
// Create channels and defer close
65+
c := make(chan numberResult)
66+
defer close(c)
67+
68+
// Execute N goroutines in range number
69+
go initGoCalculations(min, max, c)
70+
71+
for i := min; i <= max; i++ {
72+
// Receive numberResult
73+
r := <-c
74+
if r.isPrime {
75+
primeArr = append(primeArr, r.number)
76+
}
77+
}
78+
return
79+
}
80+
81+
func main() {
82+
// Receive arguments min max
83+
min, _ := strconv.ParseInt(os.Args[1], 10, 64)
84+
max, _ := strconv.ParseInt(os.Args[2], 10, 64)
85+
fmt.Println(primesInRange(min, max))
86+
}

0 commit comments

Comments
 (0)