1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | #include <stdio.h> #include <stdlib.h> #include <time.h> double slow_power(double x, int n) { int i; double r = 1.0; for (i = 0; i < n; i++) r = r * x; return (r); } double power(double x, int n) { if (n == 0) return 1; else if ((n % 2) == 0) return power(x*x, n / 2); else return x * power(x*x, (n - 1) / 2); } int main(void) { double x, value_slow, value; int n; x = 2; n = 10; value_slow = slow_power(x, n); value = power(x, n); printf("slow_power(%lf,%d) = %lf \n", x, n, value_slow); printf("power(%lf, %d) = %lf \n", x, n, value); } | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | #include <stdio.h> #include <stdlib.h> double power(double x, int n) { double value, result; printf("call power(%lf, %d) \n", x, n); if (n == 0) { printf("return 1\n"); return 1; } else if ((n % 2) == 0) { value = power(x*x, n / 2); printf("return %lf \n", value); return value; } else { value = power(x*x, (n - 1) / 2); result = x * value; printf("return %lf * %lf \n", x, value); return result; } } int main(void) { double x, value_slow, value; int n; x = 2; n = 10; value = power(x, n); printf("power(%lf, %d) = %lf \n", x, n, value); } | cs |