Skip to content

Instantly share code, notes, and snippets.

@zheltkov
Last active September 22, 2023 15:48
Show Gist options
  • Save zheltkov/43c32b73c84ba0edc50245355f1348ea to your computer and use it in GitHub Desktop.
Save zheltkov/43c32b73c84ba0edc50245355f1348ea to your computer and use it in GitHub Desktop.
n-th prime
package main
import (
"flag"
"fmt"
"math"
"sync"
"sync/atomic"
)
func main() {
numbPtr := flag.Int("n", 42, "an int")
flag.Parse()
n := *numbPtr
fmt.Println("numb:", n)
// sup := uint64(math.Exp2(float64(n)))
sup := uint64(n * int(math.Log2(float64(n))))
fmt.Println("sup:", sup)
s := make([]uint64, sup+1)
recFm := func(n uint64, j uint64) (res uint64) {
ret := uint64(1)
for n > 0 && ret != 0 {
ret = (ret * n) % j
n--
}
return ret
}
var wg sync.WaitGroup
for j := uint64(1); j <= sup; j++ {
wg.Add(1)
go func(jj uint64) {
m := (recFm(jj-1, jj) + 1%jj) % jj
s[jj] = m
wg.Done()
}(j)
if j%10000 == 0 {
fmt.Printf("progress: %.2f%%\n", 100*float64(j)/float64(sup))
wg.Wait()
}
}
wg.Wait()
fmt.Println("pre-calculated values are ready")
prime := uint64(1)
for i := uint64(1); i <= sup; i++ {
wg.Add(1)
go func(ii uint64) {
sumZnam_i := float64(0)
for j := uint64(1); j <= ii; j++ {
if s[j] == 0 {
sumZnam_i += 1
}
}
if math.Floor(math.Pow(float64(n)/sumZnam_i, 1/float64(n))) > 0 {
atomic.AddUint64(&prime, 1)
}
wg.Done()
}(i)
if i%10000 == 0 {
fmt.Printf("progress: %.2f%%\n", 100*float64(i)/float64(sup))
wg.Wait()
}
}
wg.Wait()
fmt.Println("Prime: ", prime)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment