Created
August 3, 2018 00:03
-
-
Save rain-1/79db3e3c9e1df1f800cac26ff8ab3f82 to your computer and use it in GitHub Desktop.
isqrt
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
#include <stdio.h> | |
#include <stdint.h> | |
uint64_t myisqrt(uint64_t n) { | |
int i; | |
uint64_t r, tmp; | |
r = 0; | |
for(i = 64/2-1; i >= 0; i--) { | |
tmp = r | (1 << i); | |
if(tmp*tmp <= n) r = tmp; | |
} | |
return r; | |
} | |
void test_myisqrt(uint64_t n) { | |
uint64_t r; | |
r = myisqrt(n); | |
printf("isqrt(%lu) = %lu, -^2 = %lu\n", n, r, r*r); | |
} | |
int main(void) { | |
test_myisqrt(0); | |
test_myisqrt(1); | |
test_myisqrt(2); | |
test_myisqrt(3); | |
test_myisqrt(2*2); | |
test_myisqrt(3241*3241); | |
test_myisqrt(3242*3242); | |
test_myisqrt(3243*3243); | |
test_myisqrt(55*55); | |
test_myisqrt(55*55+100); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment