Skip to content

Instantly share code, notes, and snippets.

@zeimusu
Created December 30, 2022 23:26
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 zeimusu/a099a5feb8e34e481f7d62a99d2c19ca to your computer and use it in GitHub Desktop.
Save zeimusu/a099a5feb8e34e481f7d62a99d2c19ca to your computer and use it in GitHub Desktop.
Calculate integer square root and base 2 log
package main
import (
"fmt"
)
func Iblog(n uint) uint {
i := uint(0)
for n > 1 {
n = n / 2
i += 1
}
return i
}
func Antiblog(n uint) uint {
i := uint(1)
for n > 0 {
i *= 2
n -= 1
}
return i
}
func Isqrt(n uint) uint {
if n <= 1 {
return n
}
x0 := Antiblog(Iblog(n)/2 + 1)
x1 := (x0 + n/x0) / 2
for x0 > x1 {
fmt.Println(x0, x1)
x0 = x1
x1 = (x0 + n/x0) / 2
}
return x0
}
func main() {
fmt.Println(Isqrt(7954378765))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment