Home > Article > Backend Development > Golang method to determine whether it is a prime number
How to determine prime numbers: Use a number to divide 2 to sqrt (this number)-1 respectively. If it can be divided evenly, it means that the number is not a prime number, otherwise it is a prime number.
Determine whether it is a prime number:
func IsPrime(n int) bool { if n == 1 { return false } //从2遍历到n-1,看看是否有因子 for i := 2; i < n; i++ { if n%i == 0 { //发现一个因子 return false } } return true }
Determine whether it is a prime number Optimization algorithm:
func IsPrimeII(n int) bool { //偶数一定不是素数 if n>2 && n % 2 == 0{ return true } //从2遍历到n的方根,看看是否有因子 for i := 2; i <= int(math.Ceil(math.Sqrt(float64(n)))); i++ { if n%i == 0 { //发现一个因子 return false } } return true }
For more golang knowledge, please pay attention to the golang tutorial column on the PHP Chinese website.
The above is the detailed content of Golang method to determine whether it is a prime number. For more information, please follow other related articles on the PHP Chinese website!