sieve.go 535 B

123456789101112131415161718192021222324252627282930313233343536
  1. package sieve
  2. import "log"
  3. const (
  4. Maybe = iota
  5. Prime
  6. NotPrime
  7. )
  8. func Sieve(limit int) []int {
  9. all := make([]int, limit+1)
  10. all[0] = NotPrime
  11. all[1] = NotPrime
  12. for i := 2; i <= limit; i++ {
  13. all[i] = Maybe
  14. }
  15. for i := 2; i <= limit; i++ {
  16. if all[i] == NotPrime {
  17. continue
  18. }
  19. all[i] = Prime
  20. for j := 2; j <= limit/i; j++ {
  21. all[i*j] = NotPrime
  22. }
  23. log.Printf("After %3d: %v\n", i, all)
  24. }
  25. res := make([]int, 0, len(all))
  26. for i, v := range all {
  27. if v == Prime {
  28. res = append(res, i)
  29. }
  30. }
  31. return res
  32. }