Created
October 25, 2024 12:08
-
-
Save VictoriqueMoe/0e94196ade04d43b25b055728ebeaa51 to your computer and use it in GitHub Desktop.
go prime
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
func checkPrime(given *big.Int) bool { | |
if given.Cmp(one) == 0 || given.Cmp(four) < 0 || new(big.Int).Mod(given, two).Cmp(zero) == 0 { | |
return false | |
} | |
maxN := new(big.Int).Sqrt(given).Int64() | |
for i := int64(2); i < maxN; i += 2 { | |
if new(big.Int).Mod(given, big.NewInt(i+1)).Cmp(zero) == 0 { | |
return false | |
} | |
} | |
return true | |
} | |
func main() { | |
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, big.NewInt(2)).Cmp(big.NewInt(0)) == 0 { | |
primeBefore.Sub(primeBefore, big.NewInt(1)) | |
} else { | |
primeBefore.Sub(primeBefore, big.NewInt(2)) | |
} | |
for primeBefore.Cmp(big.NewInt(0)) > 0 && !checkPrime(primeBefore) { | |
primeBefore.Sub(primeBefore, big.NewInt(2)) | |
} | |
elapsed := time.Since(start) | |
if primeBefore.Cmp(big.NewInt(0)) > 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) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment