Guest User

Untitled

a guest
Jan 22nd, 2019
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1. package main
  2.  
  3. import ("fmt"
  4. "time"
  5. )
  6.  
  7. func find_primes(max int) []int {
  8. // list of all primes that we find
  9. var primes []int
  10. primes = append(primes, 2)
  11.  
  12. var is_prime = true
  13. for i:=3; i<=max; i++ {
  14. is_prime = false
  15. // only odds can be prime
  16. if i%2 != 0 {
  17. is_prime = true
  18. // should not be divisible by any previous
  19. // prime numbers
  20. for _, x := range primes {
  21. if i%x == 0 {
  22. is_prime = false
  23. break
  24. }
  25. }
  26. }
  27. if is_prime {
  28. primes = append(primes, i)
  29. }
  30. }
  31. return primes
  32. }
  33.  
  34. // just sume up all of the primes
  35. func sum_primes(primes []int) int {
  36. var total int = 0
  37. for _, x := range primes {
  38. total = total + x
  39. }
  40. return total
  41. }
  42.  
  43. func main() {
  44. start := time.Now()
  45. // find all primes less than 2,000,000
  46. primes := find_primes(2000000)
  47. sum := sum_primes(primes)
  48. fmt.Println(sum)
  49. t := time.Now()
  50. elapsed := t.Sub(start)
  51. fmt.Println(elapsed)
  52. }
Add Comment
Please, Sign In to add comment