Construction and interpretation of SICP computer program 1.16 Iterative method logarithmic calculation of n-square of B

Source: Internet
Author: User



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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.