Created
December 30, 2022 23:26
-
-
Save zeimusu/a099a5feb8e34e481f7d62a99d2c19ca to your computer and use it in GitHub Desktop.
Calculate integer square root and base 2 log
This file contains 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" | |
) | |
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