The 1.16 iteration method calculates the n-th square of B
First, the Java implementation of the recursive and iterative method:
public class Test {public static void Main (String args[]) { int ex,ey; ex = EXPT (122,4); EY = Expt_iter (122, 4, 1); System.out.println (EY); System.out.println (ex); } recursive static int expt (int b,int n) { int sum; if (n = = 0) return 1; else { sum = (EXPT (b, (n-1))) * (b); return sum; } } Iterate static int expt_iter (int b, int counter,int product) { int sum; if (counter = = 0) { return product; } else { sum = Expt_iter (b, (counter-1), (b*product)); return sum;}} }
Again is the logarithmic iteration of scheme:
#lang racket;; N is even: B^n = (b^ (N/2)) ^2 (define (square x) (* x x)), defines the product function (define (FAST-EXPT b N), filter (expt-iter B N 1)) (Define (expt-ite R b N A) (cond (= n 0) a), when n= 0, the value is 1 ((even N) (Expt-iter (square B) (/n 2) a), and whether it is an even number (odd N) (Expt-iter b (-N 1) (* b a)))); Determine if it is an odd number (define (even n) (= (remainder n 2) 0)) (FAST-EXPT 2 15); N is odd: B^n = b*b^ (n-1)
Construction and interpretation of SICP computer program 1.16 Iterative method logarithmic calculation of n-square of B