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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
#print
Let's try a recursive function. Write a subroutine
power(x,n)
which computes x to the power n by the following
algorithm:
1. if n is zero return 1.
2. if n is odd return x*power(x,n-1).
3. if n is even return the square of
power(x,n/2).
You may assume than x and n are integers, n>=0.
If n is negative return 0 for an answer.
Put your routine on a file "power.c". Compile
it and test it; then type "ready".
#once #create tzaqc.c
main()
{
if (power(-1,-1) != 0)
return(1);
if (power(-3,2) != 9)
return(1);
if (power(2,12) != 4096)
return(1);
if (power(3,5) != 243)
return(1);
if (power(-5, 5) != -3125)
return(1);
if (power(7,3) != 343)
return(1);
if (power(7,4) != 2401)
return(1);
if (power(3,7) != 2187)
return(1);
if (power(2,10) != 1024)
return(1);
return(0);
}
#user
cc tzaqc.c power.o
a.out
#succeed
/* a possible solution */
power(x, n)
{
int k;
if (n < 0)
return(0);
if (n == 0)
return(1);
if (n%2 == 1)
return(x * power(x, n-1));
k = power(x, n/2);
return(k*k);
}
#log
#next
40.1a 10
|