Home > other >  Small white questions, prime problems
Small white questions, prime problems

Time:09-27

This code below, 1 -- 30 of prime Numbers, why in the run results 9 will be printed, should is not a prime, 9 additional runtime a number printed several times, how to modify the code to get him a number only print again,

CodePudding user response:

Judgement is prime is not playing so well

Logic has a problem, no ready-made code, see red part

 
Func putNum (numChan chan int, n int) {
For I:=2; i <=n; I++ {
NumChan & lt; -i
FMT. Println (I, "has been in the pipeline")
}
Close (numChan)
FMT. Println (" numChan closed ")
}
Func solve (numChan chan int, resultChan chan int, exitChan chan bool) {
//time. Sleep (time. Microsecond)
For {
Num, ok:=& lt; - numChan
//can't take the data out, said the current coroutines task to complete, could leave
if ! Ok {
Break
}

Flag:=true
For I:=2; i If I num %==0 {
Flag=false
Break
}
}
The if flag {
ResultChan & lt; - num
FMT. Println (" get "of prime num)
}
}

//tell the other coroutines, coroutines mission completed
ExitChan & lt; - true
FMT. Println (" a collaborators process took less than data and exit ")
}
Func main () {
NumChan:=make (chan int, 1000)
ResultChan:=make (chan int, 1000)
ExitChan:=make (chan bool, 8)
Go putNum numChan, (8000)
//open 8 collaborators cheng
For I:=0; i <8; I++ {
Go solve (numChan resultChan, exitChan)
}
//blocking the main thread, wait for after all coroutines work
Go func () {
For I:=0; i <8; I++ {
//if there is no desirable will wait
<- exitChan
}
//when after eight are close collaborators cheng can close resultChan
Close (resultChan)
FMT. Println (" resultChan closed ")
} ()
//remove the result here can be used for - range, although resultChan is closed by coroutines,
//here, but the main thread running all coroutines have to complete the task, when the resultChan must be shut down
For value:=range resultChan {
FMT. Println (value, "is a prime number")
}
FMT. Println (" the main thread to exit the ")
}

CodePudding user response:

17-29 lines, ~ ~ zha don't change color

CodePudding user response:

references and 蘤 old crepe reply: 3/f
17 to 29 lines, ~ ~ zha don't change color

So complicated, I just learned concurrent and channel, try thinking about writing your own first, seems to have learned back again wrote

CodePudding user response:

No, you want is just a fraction, the other is not, I had written many coroutines primes, you don't need to add concurrency and channels

CodePudding user response:

reference 5 floor and 蘤 old crepe reply:
no, you want is just a fraction, the other is not, I had written many coroutines prime Numbers, and you don't need to add concurrency and channel

Oh oh, I see, thank you

CodePudding user response:

Simple code it is ok to modify the

 
Func main () {
For I:=2; i <30; I++ {
J:=2
For; J & lt; i; J++ {
If I % j==0 {
Break
}
}
If I==j {
FMT. Println (I)
}
}
}


Output:
 
2
3
5
7
11.
13
17
19
23
29

  • Related