7

[Golang] Naive Method for Primality Test

 2 years ago
source link: http://siongui.github.io/2018/09/23/go-naive-method-to-check-if-a-number-is-prime-or-not/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

[Golang] Naive Method for Primality Test

September 23, 2018

Naive method for primality test in Go: Given a natural number n, if n is divisible by any number from 2 to square root of n, then n is composite. Otherwise n is prime.

Run Code on Go Playground

func IsPrime(n int) bool {
      if n < 2 {
              return false
      }

      for i := 2; i*i <= n; i++ {
              if n%i == 0 {
                      return false
              }
      }
      return true
}

Tested on: Go Playground

References:

[1][Golang] Primality Test - Optimized School Method

[2]Lemoine's Conjecture - GeeksforGeeks

[3]Lemoine’s Conjecture

[4][Golang] Sieve of Eratosthenes


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK