標籤:
使用Scheme的對數迭代法:
#lang racket;;N是偶數:b^n = (b^(n/2))^2(define (square x) (* x x));定義乘積函數(define (fast-expt b n);篩選 (expt-iter b n 1))(define (expt-iter b n a) (cond ((= n 0) a);當n= 0,值為1 ((even? n)(expt-iter (square b)(/ n 2) a));判斷是否為偶數 ((odd? n)(expt-iter b (- n 1)(* b a)))));判斷是否為奇數(define (even? n) (= (remainder n 2) 0))(fast-expt 2 15);;N是奇數:b^n = b*b^(n-1)
Java實現的遞迴法和迭代法:
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); } //遞迴 static int expt(int b,int n){ int sum; if(n == 0) return 1; else { sum = (expt(b,(n-1)))*(b); return sum; } } //迭代 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; } }}
迭代法對數計算B的N次方 SICP 電腦程式的構造和解釋 1.16