Skip to content

Instantly share code, notes, and snippets.

@rain-1
Created August 3, 2018 00:03
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 rain-1/79db3e3c9e1df1f800cac26ff8ab3f82 to your computer and use it in GitHub Desktop.
Save rain-1/79db3e3c9e1df1f800cac26ff8ab3f82 to your computer and use it in GitHub Desktop.
isqrt
#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