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++ {
        wg.Add(1)
        startTemp := (i-1)*interval + start
        endTemp := i * interval
        fmt.Printf("startTemp:%d,endTemp:%d \n", startTemp, endTemp)
        go resolve(startTemp, endTemp, resultChan,exitChan)
    }    
    wg.Add(1)
    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() {
    startTask(start, end, interval)
}

2.结果

image.png

阅读 344
71 声望
10 粉丝
0 条评论
71 声望
10 粉丝
文章目录
宣传栏