diff options
author | Ian Darwin <ian@cvs.openbsd.org> | 1998-09-28 16:01:29 +0000 |
---|---|---|
committer | Ian Darwin <ian@cvs.openbsd.org> | 1998-09-28 16:01:29 +0000 |
commit | e9be7faad5fbf61edcad3700142615e315e407bc (patch) | |
tree | 5f3febafdfca4e38b83cbc129c87aefdece9ae70 /usr.bin/learn/lib/C/L37.1a | |
parent | 0436a5b6c19a613da918536b89a49cbcb38a2e4e (diff) |
import BTL learn(1) lessons/C
Diffstat (limited to 'usr.bin/learn/lib/C/L37.1a')
-rw-r--r-- | usr.bin/learn/lib/C/L37.1a | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/usr.bin/learn/lib/C/L37.1a b/usr.bin/learn/lib/C/L37.1a new file mode 100644 index 00000000000..55a3e4c5130 --- /dev/null +++ b/usr.bin/learn/lib/C/L37.1a @@ -0,0 +1,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 |