Skip to content

Instantly share code, notes, and snippets.

@ox
Last active December 31, 2015 18:49
Show Gist options
  • Save ox/8029501 to your computer and use it in GitHub Desktop.
Save ox/8029501 to your computer and use it in GitHub Desktop.
N to the power K using optimized tail recursion
#include <stdio.h>
#include <stdlib.h>
double long npowerk(double long n, double long k) {
if (k == 0) {
return 1;
}
double long total = n;
start:
if (k <= 1) {
return total;
}
total *= n;
k--;
goto start;
}
int main(int argc, char ** argv) {
if (argc != 3) {
printf("usage: $ npowerk <int n> <int k>\n");
return 0;
}
double long a = atol(argv[1]);
double long b = atol(argv[2]);
printf("%Lf^%Lf = %Lf\n",
a, b, npowerk(a,b));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment