// version B int powerB(int x, int n) { if (n == 0) return 1; if (n == 1) return x; if (n%2 == 0) return powerB(x*x, n/2); else return powerB(x*x, n/2)*x; }
// Pre-condition: base raised to the power exp is not greater than 2^31-1, and // exp is non-negative. // Post-condition: base raised to the power exp is returned. int powerB(int base, int exp) { // Everything raised to the 0 power is 1. if (exp == 0) return 1; // Anything raised to the 1st power is itself. else if (exp == 1) return base; // Utlize the even powered exponent and the rules of exponentiation. else if (exp%2 == 0) return powerB(base*base, exp/2); // If we can't, then just use our regular solution. else return base*powerB(base, exp-1); }
int main() { // Very basic, NOT comprensive, tests of the recursive methods. int vals[4]; printf("7! = %d\n", fact(7)); printf("31^2 + 32^2 + ... + 200^2 = %d\n", sumsq(31, 200)); vals[0] = 37; vals[1] = 48; vals[2] = 56; vals[3] = 63; printf("vals has %d Odd values.\n", ArrayOdd(vals, 4)); print_reverse("writethisbackwards", 18); printf("\n"); printf("3^10 = %d\n", powerA(3,10)); printf("3^11 = %d\n", powerB(3,11)); if (Rbinary(33, vals, 0, 3) == -1) printf("33 was not found in vals.\n"); dectobin(179); printf("\n"); if (check("madamimadam", 11)) printf("madamimadam is a palindrome.\n"); printf("The 27th Fibonacci number is %d\n", fibonacci(27)); // Test of fast exponentiation vs. regular version int start = time(0); int ans1 = slowModPow(6874, 1000000000, 13713); int end1 = time(0); int ans2 = modPow(6874, 1000000000, 13713); int end2 = time(0); printf("ans1 = %d, ans2 = %d.\n", ans1, ans2); printf("slowModExp took %d sec.\n", end1-start); printf("modPow took %d sec.\n", end2-end1); system("PAUSE"); return 0; }