Skip to content

Instantly share code, notes, and snippets.

@VictoriqueMoe
Last active October 26, 2024 02:22
Show Gist options
  • Save VictoriqueMoe/7c44cfbca6c0afcc9611e3b98526f914 to your computer and use it in GitHub Desktop.
Save VictoriqueMoe/7c44cfbca6c0afcc9611e3b98526f914 to your computer and use it in GitHub Desktop.
go prime new
package main
import (
"fmt"
"math/big"
"time"
)
var one = big.NewInt(1)
var four = big.NewInt(4)
var two = big.NewInt(2)
var zero = big.NewInt(0)
var newB = new(big.Int)
const twoL = int64(2)
func checkPrime(given *big.Int) bool {
if given.Cmp(one) == 0 || given.Cmp(four) < 0 || newB.Mod(given, two).Cmp(zero) == 0 {
return false
}
maxN := newB.Sqrt(given).Int64()
for i := twoL; i < maxN; i += 2 {
if newB.Mod(given, big.NewInt(i+1)).Cmp(zero) == 0 {
return false
}
}
return true
}
func main() {
startAll := time.Now()
primesBeforeList := []*big.Int{
big.NewInt(60),
big.NewInt(6000000000),
big.NewInt(60000000000),
new(big.Int).Exp(big.NewInt(2), big.NewInt(32), nil),
new(big.Int).Exp(big.NewInt(2), big.NewInt(40), nil),
new(big.Int).Exp(big.NewInt(2), big.NewInt(44), nil),
new(big.Int).Exp(big.NewInt(2), big.NewInt(48), nil),
new(big.Int).Exp(big.NewInt(2), big.NewInt(56), nil),
new(big.Int).Exp(big.NewInt(2), big.NewInt(64), nil),
}
for _, primeBefore := range primesBeforeList {
checkingFor := new(big.Int).Set(primeBefore)
start := time.Now()
if new(big.Int).Mod(primeBefore, two).Cmp(zero) == 0 {
primeBefore.Sub(primeBefore, one)
} else {
primeBefore.Sub(primeBefore, two)
}
for primeBefore.Cmp(zero) > 0 && !checkPrime(primeBefore) {
primeBefore.Sub(primeBefore, two)
}
elapsed := time.Since(start)
if primeBefore.Cmp(zero) > 0 {
fmt.Printf("First prime before %v is %v in %v\n", checkingFor, primeBefore, elapsed)
} else {
fmt.Printf("No previous prime found in %v\n", elapsed)
}
}
elapsedAll := time.Since(startAll)
fmt.Printf("All done in %v\n", elapsedAll)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment