Advertisement
OgreVorbis

Primes Golang

Jan 3rd, 2022
1,626
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.14 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.   "fmt"
  5.   "strconv"
  6.   "time"
  7.   "math"
  8. )
  9.  
  10. func main() {
  11.     var input string
  12.     var lim int
  13.     var nums []bool
  14.     var s, n, m int
  15.    
  16.     fmt.Print("Enter limit for this search: ")
  17.     fmt.Scanln(&input)
  18.     lim, _ = strconv.Atoi(input)
  19.     if lim == 0 {
  20.       lim = 100000000
  21.     }
  22.     s = int(math.Sqrt(float64(lim)))
  23.     startTime := time.Now()
  24.     nums = make([]bool, lim + 1)
  25.     for n = 2; n < s; n++ {
  26.       if nums[n] == false {
  27.         m = n * n
  28.         for m <= lim {
  29.           nums[m] = true
  30.           m += n
  31.         }
  32.       }
  33.     }
  34.     endTime := time.Since(startTime)
  35.     fmt.Println("It took ", endTime, " time")
  36.     fmt.Print("Do you want to list results (Y/N)?")
  37.     fmt.Scanln(&input)
  38.     if input == "Y" || input == "y" {
  39.       fmt.Println("The primes up to ", lim, " are:")
  40.     } else {
  41.       fmt.Println("(please wait for prime count)")
  42.     }
  43.     m = 0
  44.     for n = 2; n < lim; n++ {
  45.       if nums[n] == false {
  46.         if input == "Y" || input == "y" {
  47.           fmt.Println(n)
  48.         }
  49.         m++
  50.       }
  51.     }
  52.     fmt.Println("")
  53.     fmt.Println("Total primes = ", m)
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement