Skip to content

Instantly share code, notes, and snippets.

@gandaro

gandaro/binexp.c Secret

Created March 5, 2012 17:29
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 gandaro/1979625 to your computer and use it in GitHub Desktop.
Save gandaro/1979625 to your computer and use it in GitHub Desktop.
Square and multiply
#include <stdio.h>
#include <stdint.h>
uint64_t bin_exp(uint32_t x, uint32_t k) {
uint64_t res = 1;
uint32_t mask = 1 << 31;
while (mask) {
res *= res;
if (k & mask)
res *= x;
mask >>= 1;
}
return res;
}
int main(void) {
for (int i = 1; i <= 15; i++)
for (int j = 2; j <= 15; j++)
printf("%d^%d = %llu\n", i, j, bin_exp(i, j));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment