5

[Golang] Primality Test - Optimized School Method

 2 years ago
source link: http://siongui.github.io/2017/04/19/go-primality-test-optimized-school-method/
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.

[Golang] Primality Test - Optimized School Method

April 19, 2017

Go implementation of primality test - optimized school method. [1]

Run Code on Go Playground

package main

import (
      "fmt"
)

func IsPrime(n int) bool {
      // Corner cases
      if n <= 1 {
              return false
      }
      if n <= 3 {
              return true
      }

      // This is checked so that we can skip
      // middle five numbers in below loop
      if n%2 == 0 || n%3 == 0 {
              return false
      }

      for i := 5; i*i <= n; i = i + 6 {
              if n%i == 0 || n%(i+2) == 0 {
                      return false
              }
      }

      return true
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK