Created
February 1, 2011 18:18
-
-
Save markandrus/806314 to your computer and use it in GitHub Desktop.
fast exponentiation
This file contains hidden or 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
| // main.c | |
| // Mark Roberts | |
| // Thanks: | |
| // http://stackoverflow.com/questions/101439 | |
| #include <stdlib.h> | |
| #include <stdio.h> | |
| #include <stdint.h> // uint64_t => [0, ULONG_LONG_MAX] | |
| // Same algorithm referenced on StackOverflow: | |
| // http://en.wikipedia.org/wiki/Modular_exponentiation | |
| uint64_t ipow(uint64_t base, uint64_t exp) { | |
| uint64_t result=1; | |
| while (exp) { | |
| if (exp&1) { | |
| result *= base; | |
| } | |
| exp >>= 1; | |
| base *= base; | |
| } | |
| return result; | |
| } | |
| int main(int argc, char **argv[]) { | |
| if (argc != 3) { | |
| fprintf(stderr, "Usage: exp BASE POW\n"); | |
| exit(2); | |
| } | |
| uint64_t a, b; | |
| if (sscanf((char *)argv[1], "%llu", &a) < 1) { // should match a uint64_t | |
| fprintf(stderr, "ERROR: `BASE' was not uint64_t\n"); // else error | |
| exit(1); | |
| } | |
| if (sscanf((char *)argv[2], "%llu", &b) < 1) { // should match a uint64_t | |
| fprintf(stderr, "ERROR: `POW' was not uint64_t\n"); // else error | |
| exit(1); | |
| } | |
| printf("%llu\n", ipow(a, b)); // print a uint64_t | |
| exit(0); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment