# golang实现计算1到100000范围内的素数

#### 1.计算1到100000范围内的素数golang实现

``````package concurrentdemo

import (
"fmt"
"sync"
)

//1-10000000

var start int = 0 //开始值

// var end int = 1000000 //结束值
var end int = 1000
var interval int = 100 //划分goroutine间隔
var wg sync.WaitGroup

func calResult(x int) bool { //素数计算函数，返回boolean类型的值
max := x/2 + 1
result := true
for i := 2; i < max; i++ {
if x%i == 0 {
result = false
break
}
}
return result
}

func startTask(start, end, interval int) { //开始任务
resultChan := make(chan int,10) //素数计算后的结果放到resultChan中
exitChan := make(chan bool,16) //为了知道各个goroutine执行完毕，然后关闭resultChan
time := (end - start) / interval //总goroutine
fmt.Printf("time:%d \n", time)
for i := 1; i <= time; i++ {
startTemp := (i-1)*interval + start
endTemp := i * interval
fmt.Printf("startTemp:%d,endTemp:%d \n", startTemp, endTemp)
go resolve(startTemp, endTemp, resultChan,exitChan)
}
go func ()  {
for i := 1; i <= time; i++ {   //循环取总time次
<- exitChan
}
wg.Done()
close(resultChan)  //在所有goroutine将自己的范围内的素数计算完之后，并发送到resultChan后，关闭resultChan
}()

for v := range resultChan{
fmt.Printf("result:%d \n",v)
}

fmt.Println("main finished")
wg.Wait()

}

func resolve(start, end int, resultChan chan<- int,exitChan chan<- bool) {
for i := start; i < end; i++ {
if calResult(i) {
resultChan <- i
}
}
exitChan <- true
fmt.Printf("start:%d,end:%d finished \n", start, end)
wg.Done()
}

func ConcurrentDemoT() {