Skip to content

Instantly share code, notes, and snippets.

@haskellcamargo
Last active March 13, 2019 12:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save haskellcamargo/82eaf3c736cf36a9684f0279c73650e3 to your computer and use it in GitHub Desktop.
Save haskellcamargo/82eaf3c736cf36a9684f0279c73650e3 to your computer and use it in GitHub Desktop.
Math.pow
#include <stdio.h>
unsigned int mult_pow(int base, unsigned int exponent) {
unsigned int result = 1;
while (1) {
if (exponent % 2 != 0) {
result *= base;
}
exponent /= 2;
if (exponent == 0) {
return result;
}
base *= base;
}
}
unsigned int bitwise_pow(int base, unsigned int exponent) {
unsigned int result = 1;
while (1) {
if ((exponent & 1) != 0) {
result *= base;
}
exponent >>= 1;
if (exponent == 0) {
return result;
}
base *= base;
}
}
int main(int argc, char** argv) {
int base = 3;
unsigned int exponent = 3;
unsigned int result = bitwise_pow(base, exponent);
printf("%d ** %d = %d", base, exponent, result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment