Annotation of 42BSD/usr.lib/learn/C/L37.1a, revision 1.1

1.1     ! root        1: #print
        !             2: Let's try a recursive function.  Write a subroutine
        !             3:     power(x,n)
        !             4: which computes x to the power n by the following
        !             5: algorithm:
        !             6:  1. if n is zero return 1.
        !             7:  2. if n is odd return x*power(x,n-1).
        !             8:  3. if n is even return the square of
        !             9:     power(x,n/2).
        !            10: You may assume than x and n are integers, n>=0.
        !            11: If n is negative return 0 for an answer.
        !            12: Put your routine on a file "power.c".  Compile
        !            13: it and test it; then type "ready".
        !            14: #once #create tzaqc.c
        !            15: main()
        !            16: {
        !            17: if (power(-1,-1) != 0) 
        !            18:                return(1);
        !            19:        if (power(-3,2) != 9) 
        !            20:                return(1);
        !            21:        if (power(2,12) != 4096) 
        !            22:                return(1);
        !            23:        if (power(3,5) !=  243) 
        !            24:                return(1);
        !            25:        if (power(-5, 5) != -3125) 
        !            26:                return(1);
        !            27:        if (power(7,3) != 343) 
        !            28:                return(1);
        !            29:        if (power(7,4) != 2401) 
        !            30:                return(1);
        !            31:        if (power(3,7) != 2187) 
        !            32:                return(1);
        !            33:        if (power(2,10) != 1024) 
        !            34:                return(1);
        !            35:        return(0);
        !            36: }
        !            37: #user
        !            38: cc tzaqc.c power.o
        !            39: a.out
        !            40: #succeed
        !            41: /*  a possible solution */
        !            42: power(x, n)
        !            43: {
        !            44:        int k;
        !            45: 
        !            46:        if (n < 0)
        !            47:                return(0);
        !            48:        if (n == 0)
        !            49:                return(1);
        !            50:        if (n%2 == 1)
        !            51:                return(x * power(x, n-1));
        !            52:        k = power(x, n/2);
        !            53:        return(k*k);
        !            54: }
        !            55: #log
        !            56: #next
        !            57: 40.1a 10

unix.superglobalmegacorp.com

This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.