Generating prime numbers in Go

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

Generating prime numbers in Go

问题

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

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

在这种情况下,每个可能的数字都会通过这些条件,但我只想让只能被自身和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:

for i := 2; i &lt;= 10; i++ {

	if i%i == 0 &amp;&amp; i%1 == 0 {

	} else {

	}
}

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

为了完整起见:

package main

import (
	"fmt"
	"math"
)

// 只会生成小于等于N的质数
const N = 100

func main() {
	var x, y, n int
	nsqrt := math.Sqrt(N)

	is_prime := [N]bool{}

	for x = 1; float64(x) <= nsqrt; x++ {
		for y = 1; float64(y) <= nsqrt; y++ {
			n = 4*(x*x) + y*y
			if n <= N && (n%12 == 1 || n%12 == 5) {
				is_prime[n] = !is_prime[n]
			}
			n = 3*(x*x) + y*y
			if n <= N && n%12 == 7 {
				is_prime[n] = !is_prime[n]
			}
			n = 3*(x*x) - y*y
			if x > y && n <= N && n%12 == 11 {
				is_prime[n] = !is_prime[n]
			}
		}
	}

	for n = 5; float64(n) <= nsqrt; n++ {
		if is_prime[n] {
			for y = n * n; y < N; y += n * n {
				is_prime[y] = false
			}
		}
	}

	is_prime[2] = true
	is_prime[3] = true

	primes := make([]int, 0, 1270606)
	for x = 0; x < len(is_prime)-1; x++ {
		if is_prime[x] {
			primes = append(primes, x)
		}
	}

	// primes现在是一个包含所有小于等于N的质数的切片
	// 让我们打印它们
	for _, x := range primes {
		fmt.Println(x)
	}
}
英文:

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:

package main

import (
	&quot;fmt&quot;
	&quot;math&quot;
)

// Only primes less than or equal to N will be generated
const N = 100

func main() {
	var x, y, n int
	nsqrt := math.Sqrt(N)

	is_prime := [N]bool{}

	for x = 1; float64(x) &lt;= nsqrt; x++ {
		for y = 1; float64(y) &lt;= nsqrt; y++ {
			n = 4*(x*x) + y*y
			if n &lt;= N &amp;&amp; (n%12 == 1 || n%12 == 5) {
				is_prime[n] = !is_prime[n]
			}
			n = 3*(x*x) + y*y
			if n &lt;= N &amp;&amp; n%12 == 7 {
				is_prime[n] = !is_prime[n]
			}
			n = 3*(x*x) - y*y
			if x &gt; y &amp;&amp; n &lt;= N &amp;&amp; n%12 == 11 {
				is_prime[n] = !is_prime[n]
			}
		}
	}

	for n = 5; float64(n) &lt;= nsqrt; n++ {
		if is_prime[n] {
			for y = n * n; y &lt; N; y += n * n {
				is_prime[y] = false
			}
		}
	}

	is_prime[2] = true
	is_prime[3] = true

	primes := make([]int, 0, 1270606)
	for x = 0; x &lt; len(is_prime)-1; x++ {
		if is_prime[x] {
			primes = append(primes, x)
		}
	}

	// primes is now a slice that contains all primes numbers up to N
	// so let&#39;s print them
	for _, x := range primes {
		fmt.Println(x)
	}
}

答案2

得分: 8

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

package main
import "fmt"

// 返回小于N的质数列表
func sieveOfEratosthenes(N int) (primes []int) {
    b := make([]bool, N)
    for i := 2; i < N; i++ {
        if b[i] == true { continue }
        primes = append(primes, i)
        for k := i * i; k < N; k += i {
            b[k] = true
        }
    }
    return
}

func main() {
    primes := sieveOfEratosthenes(100)
    for _, p := range primes {
        fmt.Println(p)
    }
}

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

英文:

Here's a golang sieve of Eratosthenes

package main
import &quot;fmt&quot;

// return list of primes less than N
func sieveOfEratosthenes(N int) (primes []int) {
    b := make([]bool, N)
    for i := 2; i &lt; N; i++ {
        if b[i] == true { continue }
        primes = append(primes, i)
        for k := i * i; k &lt; N; k += i {
            b[k] = true
        }
    }
    return
}

func main() {
    primes := sieveOfEratosthenes(100)
    for _, p := range primes {
        fmt.Println(p)
    }
}

答案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):

import (
	"fmt"
	"math/big"
)

func main() {
	for i := 2; i < 1000; i++ {
		if big.NewInt(int64(i)).ProbablyPrime(20) {
			fmt.Printf("%d 可能是质数\n", i)
		} else {
			fmt.Printf("%d 绝对不是质数\n", i)
		}
	}
}

只需将常量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)

import (
	&quot;fmt&quot;
	&quot;math/big&quot;
)

func main() {
	for i := 2; i &lt; 1000; i++ {
		if big.NewInt(int64(i)).ProbablyPrime(20) {
			fmt.Printf(&quot;%d is probably prime\n&quot;, i)
		} else {
			fmt.Printf(&quot;%d is definitely not prime\n&quot;, i)
		}
	}
}

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

答案5

得分: 1

简单的方式(修正):

package main

import "math"

const n = 100

func main() {
    print(1, " ", 2)

L:  for i := 3; i <= n; i += 2 {
        m := int(math.Floor(math.Sqrt(float64(i))))
        for j := 2; j <= m; j++ {
            if i%j == 0 {
                continue L
            }
        }
        print(" ", i)
    }
}

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

英文:

Simple way(fixed):

package main

import &quot;math&quot;

const n = 100

func main() {
    print(1, &quot; &quot;, 2)

L:	for i := 3; i &lt;= n; i += 2 {
	    m := int(math.Floor(math.Sqrt(float64(i))))
	    for j := 2; j &lt;= m; j++ {
		    if i%j == 0 {
			    continue L
		    }
	    }
	    print(&quot; &quot;, i)
    }
}

答案6

得分: 1

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

	for i:=2; i<=100; i++{


		isPrime:=true

		for j:=2; j<i; j++{

			if i % j == 0 {

				isPrime = false
			}
		}
		
		if isPrime == true {

			fmt.Println(i)
		} 
	}


}
英文:

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

	for i:=2; i&lt;=100; i++{


		isPrime:=true

		for j:=2; j&lt;i; j++{

			if i % j == 0 {

				isPrime = false
			}
		}
		
		if isPrime == true {

			fmt.Println(i)
		} 
	}


}

答案7

得分: 0

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

package main

import (
	"math"
	"time"
	"fmt"
)

func prime(n int) bool {

	if n < 1 {
		return false
	}

	if n == 2 {
		return true
	}

	if n % 2 == 0 && n > 2 {
		return false
	}

	var maxDivisor = int(math.Floor(math.Sqrt(float64 (n))))

	//d := 3
	for d:=3 ;d <= 1 + maxDivisor; d += 2 {

		if n%d == 0 {
			return false
		}
	}
	return true
}
//======Test Function=====

func main() {
	// var t0 = time.Time{}
	var t0= time.Second
	for i := 1; i <= 1000; i++ {
		fmt.Println(prime(i))
	}
	var t1= time.Second
	println(t1 - t0)
}

这段代码是一个用于判断素数的函数。它通过检查给定的数字是否能被除了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.

package main

import (
	&quot;math&quot;
	&quot;time&quot;
	&quot;fmt&quot;
)

func prime(n int) bool {

	if n &lt; 1 {
		return false
	}

	if n == 2 {
		return true
	}

	if n % 2 == 0 &amp;&amp; n &gt; 2 {
		return false
	}

	var maxDivisor = int(math.Floor(math.Sqrt(float64 (n))))

	//d := 3
	for d:=3 ;d &lt;= 1 + maxDivisor; d += 2 {

		if n%d == 0 {
			return false
		}
	}
	return true
}
//======Test Function=====

func main() {
	// var t0 = time.Time{}
	var t0= time.Second
	for i := 1; i &lt;= 1000; i++ {
		fmt.Println(prime(i))
	}
	var t1= time.Second
	println(t1 - t0)
}

答案8

得分: 0

package main

import (
	"fmt"
)

func main() {
	//runtime.GOMAXPROCS(4)

	ch := make(chan int)
	go generate(ch)
	for {
		prime := <-ch
		fmt.Println(prime)
		ch1 := make(chan int)
		go filter(ch, ch1, prime)
		ch = ch1
	}
}

func generate(ch chan int) {
	for i := 2; ; i++ {
		ch <- i
	}
}

func filter(in, out chan int, prime int) {
	for {
		i := <-in
		if i%prime != 0 {
			out <- i
		}
	}
}

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

英文:
package main

import (
	&quot;fmt&quot;
)

func main() {
	//runtime.GOMAXPROCS(4)

	ch := make(chan int)
	go generate(ch)
	for {
		prime := &lt;-ch
		fmt.Println(prime)
		ch1 := make(chan int)
		go filter(ch, ch1, prime)
		ch = ch1
	}
}

func generate(ch chan int) {
	for i := 2; ; i++ {
		ch &lt;- i
	}
}

func filter(in, out chan int, prime int) {
	for {
		i := &lt;-in
		if i%prime != 0 {
			out &lt;- i
		}
	}
}

答案9

得分: 0

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

package main
import "fmt"

func main() {
    var num = 1000
    for j := 2; j < num  ; j++ {
        var flag = 0
        for i := 2; i <= j/2  ; i++ {    
            if j % i == 0 {
                flag = 1
                break
            }
        }
        if flag == 0 {
            fmt.Println(j)
        }
    }

}
英文:

A C like logic (old school),

package main
import &quot;fmt&quot;

func main() {
	var num = 1000
	for j := 2; j &lt; num  ; j++ {
		var flag = 0
		for i := 2; i &lt;= j/2  ; i++ {	
			if j % i == 0 {
				flag = 1
				break
			}
		}
		if flag == 0 {
			fmt.Println(j)
		}
	}

}

答案10

得分: 0

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

func findNthPrime(number int) int {

    if number < 1{
		fmt.Println("请提供正数")
		return number
	}

	var primeCounter, nthPrimeNumber int

	for i:=2; primeCounter < number; i++{
		isPrime := true
		for j:=2; j <= int(math.Sqrt(float64(i))) && i != 2  ; j++{
			if i % j == 0{
				isPrime = false
			}
		}
		if isPrime{
			primeCounter++
			nthPrimeNumber = i
            fmt.Println(primeCounter, "th prime number is ", nthPrimeNumber)
		}
	}
	fmt.Println("第", number, "个素数是", nthPrimeNumber)
	return nthPrimeNumber
}
英文:

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

func findNthPrime(number int) int {

    if number &lt; 1{
		fmt.Println(&quot;Please provide positive number&quot;)
		return number
	}

	var primeCounter, nthPrimeNumber int

	for i:=2; primeCounter &lt; number; i++{
		isPrime := true
		for j:=2; j &lt;= int(math.Sqrt(float64(i))) &amp;&amp; i != 2  ; j++{
			if i % j == 0{
				isPrime = false
			}
		}
		if isPrime{
			primeCounter++
			nthPrimeNumber = i
            fmt.Println(primeCounter, &quot;th prime number is &quot;, nthPrimeNumber)
		}
	}
	fmt.Println(&quot;Nth prime number is &quot;, nthPrimeNumber)
	return nthPrimeNumber
}

答案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:

确定