fork download
  1. package main
  2.  
  3. import (
  4. "fmt"
  5. )
  6.  
  7. type PrimeGenerator struct {
  8. primeChan chan uint32
  9. }
  10.  
  11. func NewPrimeGenerator() *PrimeGenerator {
  12. primeGenerator := PrimeGenerator{
  13. primeChan: make(chan uint32),
  14. }
  15.  
  16. go primeGenerator.start()
  17.  
  18. return &primeGenerator
  19. }
  20.  
  21. func (p *PrimeGenerator) start() {
  22. multiples := map[uint32]uint32{}
  23.  
  24. p.primeChan <- 2
  25. for num := uint32(3); ; num += 2 {
  26. factor, hasFactor := multiples[num]
  27. if hasFactor {
  28. delete(multiples, num)
  29. } else {
  30. factor = num << 1
  31. }
  32.  
  33. for newNum := num + factor; ; newNum += factor {
  34. _, hasNewFactor := multiples[newNum]
  35. if !hasNewFactor {
  36. multiples[newNum] = factor
  37. break
  38. }
  39. }
  40.  
  41. if !hasFactor {
  42. p.primeChan <- num
  43. }
  44. }
  45. }
  46.  
  47. func (p *PrimeGenerator) Next() uint32 {
  48. return <- p.primeChan
  49. }
  50.  
  51. func main() {
  52. n := 1000000
  53. primeGenerator := NewPrimeGenerator()
  54. for i := 1; i < n; i++ {
  55. primeGenerator.Next()
  56. }
  57. fmt.Printf("%d番目の素数: %d", n, primeGenerator.Next())
  58. }
Success #stdin #stdout 2.28s 49712KB
stdin
Standard input is empty
stdout
1000000番目の素数: 15485863