Generating prime numbers in Go

huangapple go评论129阅读模式
英文:

Generating prime numbers in Go

问题

我希望我的if语句只在满足以下两个条件时为真:

  1. for i := 2; i <= 10; i++ {
  2. if i%i == 0 && i%1 == 0 {
  3. // 满足条件的情况
  4. } else {
  5. // 不满足条件的情况
  6. }
  7. }

在这种情况下,每个可能的数字都会通过这些条件,但我只想让只能被自身和1整除的数字通过,除了第一个数字'2'之外。我该如何做到这一点?

谢谢

英文:

EDIT: The question essentially asks to generate prime numbers up to a certain limit. The original question follows.

I want my if statement to become true if only these two conditions are met:

  1. for i := 2; i &lt;= 10; i++ {
  2. if i%i == 0 &amp;&amp; i%1 == 0 {
  3. } else {
  4. }
  5. }

In this case every possible number gets past these conditions, however I want only the numbers 2, 3, 5, 7, 11... basically numbers that are divisible only with themselves and by 1 to get past, with the exception being the very first '2'. How can I do this?

Thanks

答案1

得分: 14

似乎你正在寻找质数。然而,你描述的条件是不充分的。实际上,你需要使用一个算法来生成它们(最可能是在一定的限制范围内)。

这是一个实现 Atkin筛法 的代码,它是古老的埃拉托斯特尼筛法的优化变体。

演示:http://play.golang.org/p/XXiTIpRBAu

为了完整起见:

  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. )
  6. // 只会生成小于等于N的质数
  7. const N = 100
  8. func main() {
  9. var x, y, n int
  10. nsqrt := math.Sqrt(N)
  11. is_prime := [N]bool{}
  12. for x = 1; float64(x) <= nsqrt; x++ {
  13. for y = 1; float64(y) <= nsqrt; y++ {
  14. n = 4*(x*x) + y*y
  15. if n <= N && (n%12 == 1 || n%12 == 5) {
  16. is_prime[n] = !is_prime[n]
  17. }
  18. n = 3*(x*x) + y*y
  19. if n <= N && n%12 == 7 {
  20. is_prime[n] = !is_prime[n]
  21. }
  22. n = 3*(x*x) - y*y
  23. if x > y && n <= N && n%12 == 11 {
  24. is_prime[n] = !is_prime[n]
  25. }
  26. }
  27. }
  28. for n = 5; float64(n) <= nsqrt; n++ {
  29. if is_prime[n] {
  30. for y = n * n; y < N; y += n * n {
  31. is_prime[y] = false
  32. }
  33. }
  34. }
  35. is_prime[2] = true
  36. is_prime[3] = true
  37. primes := make([]int, 0, 1270606)
  38. for x = 0; x < len(is_prime)-1; x++ {
  39. if is_prime[x] {
  40. primes = append(primes, x)
  41. }
  42. }
  43. // primes现在是一个包含所有小于等于N的质数的切片
  44. // 让我们打印它们
  45. for _, x := range primes {
  46. fmt.Println(x)
  47. }
  48. }
英文:

It seems you are looking for prime numbers. However the conditions you described are not sufficient. In fact you have to use an algorithm to generate them (up to a certain limit most probably).

This is an implementation of the Sieve of Atkin which is an optimized variation of the ancient Sieve of Eratosthenes.

Demo: http://play.golang.org/p/XXiTIpRBAu

For the sake of completeness:

  1. package main
  2. import (
  3. &quot;fmt&quot;
  4. &quot;math&quot;
  5. )
  6. // Only primes less than or equal to N will be generated
  7. const N = 100
  8. func main() {
  9. var x, y, n int
  10. nsqrt := math.Sqrt(N)
  11. is_prime := [N]bool{}
  12. for x = 1; float64(x) &lt;= nsqrt; x++ {
  13. for y = 1; float64(y) &lt;= nsqrt; y++ {
  14. n = 4*(x*x) + y*y
  15. if n &lt;= N &amp;&amp; (n%12 == 1 || n%12 == 5) {
  16. is_prime[n] = !is_prime[n]
  17. }
  18. n = 3*(x*x) + y*y
  19. if n &lt;= N &amp;&amp; n%12 == 7 {
  20. is_prime[n] = !is_prime[n]
  21. }
  22. n = 3*(x*x) - y*y
  23. if x &gt; y &amp;&amp; n &lt;= N &amp;&amp; n%12 == 11 {
  24. is_prime[n] = !is_prime[n]
  25. }
  26. }
  27. }
  28. for n = 5; float64(n) &lt;= nsqrt; n++ {
  29. if is_prime[n] {
  30. for y = n * n; y &lt; N; y += n * n {
  31. is_prime[y] = false
  32. }
  33. }
  34. }
  35. is_prime[2] = true
  36. is_prime[3] = true
  37. primes := make([]int, 0, 1270606)
  38. for x = 0; x &lt; len(is_prime)-1; x++ {
  39. if is_prime[x] {
  40. primes = append(primes, x)
  41. }
  42. }
  43. // primes is now a slice that contains all primes numbers up to N
  44. // so let&#39;s print them
  45. for _, x := range primes {
  46. fmt.Println(x)
  47. }
  48. }

答案2

得分: 8

这是一个使用Go语言实现的埃拉托斯特尼筛法:

  1. package main
  2. import "fmt"
  3. // 返回小于N的质数列表
  4. func sieveOfEratosthenes(N int) (primes []int) {
  5. b := make([]bool, N)
  6. for i := 2; i < N; i++ {
  7. if b[i] == true { continue }
  8. primes = append(primes, i)
  9. for k := i * i; k < N; k += i {
  10. b[k] = true
  11. }
  12. }
  13. return
  14. }
  15. func main() {
  16. primes := sieveOfEratosthenes(100)
  17. for _, p := range primes {
  18. fmt.Println(p)
  19. }
  20. }

这段代码实现了埃拉托斯特尼筛法,用于找出小于N的所有质数。在主函数中,我们调用sieveOfEratosthenes函数并打印出返回的质数列表。

英文:

Here's a golang sieve of Eratosthenes

  1. package main
  2. import &quot;fmt&quot;
  3. // return list of primes less than N
  4. func sieveOfEratosthenes(N int) (primes []int) {
  5. b := make([]bool, N)
  6. for i := 2; i &lt; N; i++ {
  7. if b[i] == true { continue }
  8. primes = append(primes, i)
  9. for k := i * i; k &lt; N; k += i {
  10. b[k] = true
  11. }
  12. }
  13. return
  14. }
  15. func main() {
  16. primes := sieveOfEratosthenes(100)
  17. for _, p := range primes {
  18. fmt.Println(p)
  19. }
  20. }

答案3

得分: 5

获取“只能被自身和1整除”的数字,也被称为质数的最简单方法是:http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

这不是一个“简单的if语句”。

英文:

The simplest method to get "numbers that are divisible only with themselves and by 1", which are also known as prime numbers is: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

It's not a "simple if statement".

答案4

得分: 1

如果你不介意它们可能不是质数的非常小的几率(在这种情况下为9.1e-13),你可以像这样使用math/big中的ProbablyPrime函数(play):

  1. import (
  2. "fmt"
  3. "math/big"
  4. )
  5. func main() {
  6. for i := 2; i < 1000; i++ {
  7. if big.NewInt(int64(i)).ProbablyPrime(20) {
  8. fmt.Printf("%d 可能是质数\n", i)
  9. } else {
  10. fmt.Printf("%d 绝对不是质数\n", i)
  11. }
  12. }
  13. }

只需将常量20更改为你认为足够确定它们是质数的值。

英文:

If you don't mind a very small chance (9.1e-13 in this case) of them not being primes you can use ProbablyPrime from math/big like this (play)

  1. import (
  2. &quot;fmt&quot;
  3. &quot;math/big&quot;
  4. )
  5. func main() {
  6. for i := 2; i &lt; 1000; i++ {
  7. if big.NewInt(int64(i)).ProbablyPrime(20) {
  8. fmt.Printf(&quot;%d is probably prime\n&quot;, i)
  9. } else {
  10. fmt.Printf(&quot;%d is definitely not prime\n&quot;, i)
  11. }
  12. }
  13. }

Just change the constant 20 to be as sure as you like that they are primes.

答案5

得分: 1

简单的方式(修正):

  1. package main
  2. import "math"
  3. const n = 100
  4. func main() {
  5. print(1, " ", 2)
  6. L: for i := 3; i <= n; i += 2 {
  7. m := int(math.Floor(math.Sqrt(float64(i))))
  8. for j := 2; j <= m; j++ {
  9. if i%j == 0 {
  10. continue L
  11. }
  12. }
  13. print(" ", i)
  14. }
  15. }

以上是给定的代码段,它使用简单的方式来打印出从1到100之间的所有素数。

英文:

Simple way(fixed):

  1. package main
  2. import &quot;math&quot;
  3. const n = 100
  4. func main() {
  5. print(1, &quot; &quot;, 2)
  6. L: for i := 3; i &lt;= n; i += 2 {
  7. m := int(math.Floor(math.Sqrt(float64(i))))
  8. for j := 2; j &lt;= m; j++ {
  9. if i%j == 0 {
  10. continue L
  11. }
  12. }
  13. print(&quot; &quot;, i)
  14. }
  15. }

答案6

得分: 1

只需将外部循环中的100更改为您想要找到的质数的限制即可。干杯!

  1. for i:=2; i<=100; i++{
  2. isPrime:=true
  3. for j:=2; j<i; j++{
  4. if i % j == 0 {
  5. isPrime = false
  6. }
  7. }
  8. if isPrime == true {
  9. fmt.Println(i)
  10. }
  11. }
  12. }
英文:

just change the 100 in the outer for loop to the limit of the prime number you want to find. cheers!!

  1. for i:=2; i&lt;=100; i++{
  2. isPrime:=true
  3. for j:=2; j&lt;i; j++{
  4. if i % j == 0 {
  5. isPrime = false
  6. }
  7. }
  8. if isPrime == true {
  9. fmt.Println(i)
  10. }
  11. }
  12. }

答案7

得分: 0

请尝试这个代码,通过检查所有边界情况和优化的方式来找到数字,并在函数返回true时运行逻辑。

  1. package main
  2. import (
  3. "math"
  4. "time"
  5. "fmt"
  6. )
  7. func prime(n int) bool {
  8. if n < 1 {
  9. return false
  10. }
  11. if n == 2 {
  12. return true
  13. }
  14. if n % 2 == 0 && n > 2 {
  15. return false
  16. }
  17. var maxDivisor = int(math.Floor(math.Sqrt(float64 (n))))
  18. //d := 3
  19. for d:=3 ;d <= 1 + maxDivisor; d += 2 {
  20. if n%d == 0 {
  21. return false
  22. }
  23. }
  24. return true
  25. }
  26. //======Test Function=====
  27. func main() {
  28. // var t0 = time.Time{}
  29. var t0= time.Second
  30. for i := 1; i <= 1000; i++ {
  31. fmt.Println(prime(i))
  32. }
  33. var t1= time.Second
  34. println(t1 - t0)
  35. }

这段代码是一个用于判断素数的函数。它通过检查给定的数字是否能被除了1和自身以外的其他数字整除来确定是否为素数。在main函数中,它会打印从1到1000的所有数字是否为素数,并计算执行时间。

英文:

Here try this by checking all corner cases and optimised way to find you numbers and run the logic when the function returns true.

  1. package main
  2. import (
  3. &quot;math&quot;
  4. &quot;time&quot;
  5. &quot;fmt&quot;
  6. )
  7. func prime(n int) bool {
  8. if n &lt; 1 {
  9. return false
  10. }
  11. if n == 2 {
  12. return true
  13. }
  14. if n % 2 == 0 &amp;&amp; n &gt; 2 {
  15. return false
  16. }
  17. var maxDivisor = int(math.Floor(math.Sqrt(float64 (n))))
  18. //d := 3
  19. for d:=3 ;d &lt;= 1 + maxDivisor; d += 2 {
  20. if n%d == 0 {
  21. return false
  22. }
  23. }
  24. return true
  25. }
  26. //======Test Function=====
  27. func main() {
  28. // var t0 = time.Time{}
  29. var t0= time.Second
  30. for i := 1; i &lt;= 1000; i++ {
  31. fmt.Println(prime(i))
  32. }
  33. var t1= time.Second
  34. println(t1 - t0)
  35. }

答案8

得分: 0

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func main() {
  6. //runtime.GOMAXPROCS(4)
  7. ch := make(chan int)
  8. go generate(ch)
  9. for {
  10. prime := <-ch
  11. fmt.Println(prime)
  12. ch1 := make(chan int)
  13. go filter(ch, ch1, prime)
  14. ch = ch1
  15. }
  16. }
  17. func generate(ch chan int) {
  18. for i := 2; ; i++ {
  19. ch <- i
  20. }
  21. }
  22. func filter(in, out chan int, prime int) {
  23. for {
  24. i := <-in
  25. if i%prime != 0 {
  26. out <- i
  27. }
  28. }
  29. }

这是一个使用Go语言编写的简单程序。它实现了一个无限生成素数的算法。程序通过使用goroutine和通道来实现并发计算。在主函数中,首先创建了一个整数类型的通道ch,并启动了一个goroutine来生成素数,并将素数发送到通道ch中。然后,通过一个无限循环,从通道ch中接收素数,并打印出来。接着,创建了一个新的通道ch1,并启动一个goroutine来过滤掉不是素数的数,并将结果发送到通道ch1中。最后,将通道ch1赋值给通道ch,继续下一轮循环。这样就实现了一个无限生成素数的算法。

英文:
  1. package main
  2. import (
  3. &quot;fmt&quot;
  4. )
  5. func main() {
  6. //runtime.GOMAXPROCS(4)
  7. ch := make(chan int)
  8. go generate(ch)
  9. for {
  10. prime := &lt;-ch
  11. fmt.Println(prime)
  12. ch1 := make(chan int)
  13. go filter(ch, ch1, prime)
  14. ch = ch1
  15. }
  16. }
  17. func generate(ch chan int) {
  18. for i := 2; ; i++ {
  19. ch &lt;- i
  20. }
  21. }
  22. func filter(in, out chan int, prime int) {
  23. for {
  24. i := &lt;-in
  25. if i%prime != 0 {
  26. out &lt;- i
  27. }
  28. }
  29. }

答案9

得分: 0

一个类似C语言(老派)的逻辑,

  1. package main
  2. import "fmt"
  3. func main() {
  4. var num = 1000
  5. for j := 2; j < num ; j++ {
  6. var flag = 0
  7. for i := 2; i <= j/2 ; i++ {
  8. if j % i == 0 {
  9. flag = 1
  10. break
  11. }
  12. }
  13. if flag == 0 {
  14. fmt.Println(j)
  15. }
  16. }
  17. }
英文:

A C like logic (old school),

  1. package main
  2. import &quot;fmt&quot;
  3. func main() {
  4. var num = 1000
  5. for j := 2; j &lt; num ; j++ {
  6. var flag = 0
  7. for i := 2; i &lt;= j/2 ; i++ {
  8. if j % i == 0 {
  9. flag = 1
  10. break
  11. }
  12. }
  13. if flag == 0 {
  14. fmt.Println(j)
  15. }
  16. }
  17. }

答案10

得分: 0

生成小于某个限制的素数的简单解决方案:

  1. func findNthPrime(number int) int {
  2. if number < 1{
  3. fmt.Println("请提供正数")
  4. return number
  5. }
  6. var primeCounter, nthPrimeNumber int
  7. for i:=2; primeCounter < number; i++{
  8. isPrime := true
  9. for j:=2; j <= int(math.Sqrt(float64(i))) && i != 2 ; j++{
  10. if i % j == 0{
  11. isPrime = false
  12. }
  13. }
  14. if isPrime{
  15. primeCounter++
  16. nthPrimeNumber = i
  17. fmt.Println(primeCounter, "th prime number is ", nthPrimeNumber)
  18. }
  19. }
  20. fmt.Println("第", number, "个素数是", nthPrimeNumber)
  21. return nthPrimeNumber
  22. }
英文:

Simple solution for generating prime numbers up to a certain limit:

  1. func findNthPrime(number int) int {
  2. if number &lt; 1{
  3. fmt.Println(&quot;Please provide positive number&quot;)
  4. return number
  5. }
  6. var primeCounter, nthPrimeNumber int
  7. for i:=2; primeCounter &lt; number; i++{
  8. isPrime := true
  9. for j:=2; j &lt;= int(math.Sqrt(float64(i))) &amp;&amp; i != 2 ; j++{
  10. if i % j == 0{
  11. isPrime = false
  12. }
  13. }
  14. if isPrime{
  15. primeCounter++
  16. nthPrimeNumber = i
  17. fmt.Println(primeCounter, &quot;th prime number is &quot;, nthPrimeNumber)
  18. }
  19. }
  20. fmt.Println(&quot;Nth prime number is &quot;, nthPrimeNumber)
  21. return nthPrimeNumber
  22. }

答案11

得分: -1

质数是只能被1和自身整除的正整数。例如:2、3、5、7、11、13、17。
什么是质数?
质数是一个不能通过其他整数相乘得到的整数。

质数(或质数)是大于1且不是两个较小的自然数的乘积的自然数。大于1且不是质数的自然数被称为合数。
用Go语言编写的检查一个数是否为质数的程序
https://www.golanguagehub.com/2021/01/primenumber.html

英文:

A prime number is a positive integer that is divisible only by 1 and itself. For example: 2, 3, 5, 7, 11, 13, 17.
What is Prime Number?
A Prime Number is a whole number that cannot be made by multiplying other whole numbers

A prime number (or a prime) is a natural number greater than 1 that is not a product of two smaller natural numbers. A natural number greater than 1 that is not prime is called a composite number.
Go Language Program to Check Whether a Number is Prime or Not
https://www.golanguagehub.com/2021/01/primenumber.html

huangapple
  • 本文由 发表于 2014年2月18日 20:41:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/21854191.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定