迭代法对数计算B的N次方 SICP 计算机程序的构造和解释 1.16

使用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;
        }
    }
}

 

posted @ 2015-01-20 17:32  Pxjw  阅读(947)  评论(0编辑  收藏  举报