Skip to content

Instantly share code, notes, and snippets.

@OrangeTide
Created April 14, 2011 19:39
Show Gist options
  • Save OrangeTide/920300 to your computer and use it in GitHub Desktop.
Save OrangeTide/920300 to your computer and use it in GitHub Desktop.
integer pow() using Montgomery's ladder
/* Montgomery's Ladder Technique
* http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.5.4956&rep=rep1&type=pdf
*/
#include <stdio.h>
#include <limits.h>
static unsigned long long ipow(unsigned g, unsigned k)
{
unsigned long long r0, r1;
unsigned j;
r0 = 1;
r1 = g;
/* you can also set j to the position of the top most 1 bit */
for (j = sizeof(k) * CHAR_BIT; j--; ) {
/*
fprintf(stderr, "\t[%d] r0 = %llu; r1 = %llu\n", j, r0, r1);
*/
if ((k >> j) & 1) {
r0 = r0 * r1;
r1 = r1 * r1;
} else {
r1 = r0 * r1;
r0 = r0 * r0;
}
}
return r0;
}
static void ladder_test(unsigned g, unsigned k)
{
unsigned long long r;
r = ipow(g, k);
fprintf(stdout, "%u^%u = %llu\n", g, k, r);
}
int main()
{
ladder_test(3, 30);
ladder_test(64, 7);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment