示例#1
0
int powerA(int x, int n)
{
  if (n == 0)
    return 1;
  if (n == 1)
    return x;
  else
    return x * powerA(x, n - 1);
}
示例#2
0
// 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 powerA(int base, int exp) {
    
    // Everything raised to the 0 power is 1.
    if (exp == 0)
        return 1;
        
    // Apply the recursive algorithm to solve the problem.
    else
        return base*powerA(base, exp-1);
}
示例#3
0
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;
}