Skip to content

Instantly share code, notes, and snippets.

@lzap
Created March 17, 2023 06:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lzap/a0bcd60478272cc681e8f44717b18614 to your computer and use it in GitHub Desktop.
Save lzap/a0bcd60478272cc681e8f44717b18614 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"time"
)
func main() {
start := time.Now()
_ = p0(200_000)
fmt.Printf("The original: %v ms\n", time.Since(start).Milliseconds())
start = time.Now()
_ = p1(200_000)
fmt.Printf("Without slice (int): %v ms\n", time.Since(start).Milliseconds())
start = time.Now()
_ = p2(int32(200_000))
fmt.Printf("Without slice (int32) %v ms\n", time.Since(start).Milliseconds())
}
func p0(limit int) int {
var lastPrime int
primes := []int{}
for x := 2; x < limit; x++ {
is_prime := true
for y := 2; y < x; y++ {
if x%y == 0 {
is_prime = false
break
}
}
if is_prime {
primes = append(primes, x)
lastPrime = x
}
}
return lastPrime
}
func p1(limit int) int {
var lastPrime int
for x := 2; x < limit; x++ {
isPrime := true
for y := 2; y < x; y++ {
if x%y == 0 {
isPrime = false
break
}
}
if isPrime {
lastPrime = x
}
}
return lastPrime
}
func p2(limit int32) int32 {
var lastPrime int32
var x, y int32
for x = 2; x < limit; x++ {
isPrime := true
for y = 2; y < x; y++ {
if x%y == 0 {
isPrime = false
break
}
}
if isPrime {
lastPrime = x
}
}
return lastPrime
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment