sicp - 我不明白这两个变量是如何成比例的
问题描述
计算机程序的结构和解释第 1.2.1 节线性递归和迭代:
比较这两个过程......每个过程都需要与 n 成比例的步骤来计算 n!
这两个过程由
(define (factorial n)
(if (= n 1)
1
(* n (factorial (- n 1)))))
;; This is the linear recursive process
(define (factorial n)
(define (iter product counter)
(if (> counter n)
product
(iter (* counter product)
(+ counter 1))))
(iter 1 1))
;; This is the linear iterative process
我的问题是:这两个过程如何需要与 n 成比例的步骤来计算 n!?
解决方案
对于第一个过程;您必须在一个递归循环中执行这些步骤:
- check if n equals 1
- multiply n with (factorial (- n 1))
if we split it a little, it includes (- n 1) and a function call and a multiplication.
让我们粗略地将这些视为 4 个步骤。
而且因为您必须执行这 4 个步骤直到 n = 1,所以总共是 4*n 步骤。所以它与n成正比。(我们忽略一些细节,例如,n=1 情况的处理有点不同,因为当 n 足够大时,可以忽略)
第二个是一样的
推荐阅读
- javascript - 尝试在 react-router 中实现 react-transition-group 会产生错误:'元素类型无效......'
- scala - Scala 中间早期初始化器
- c# - XAML 中使用 Lambda 表达式和 MVVM 模式的 OneWay/TwoWay 绑定
- android - 构建项目时出现重复的类错误
- regex - 替换文件中的分隔符而不更改引号之间的值
- android - WiFi网络连接在Android Q上不断断开
- graphql - 如何使用 Apollo 客户端 websocket 处理注销/登录并保持有效订阅?
- python-3.x - 根据来自其他数据框 pandas 的信息添加列
- javascript - Ajax 问题基于类别在 foreach 内加载更多 CPT 循环请求
- c++ - 从 CMake 中的 lib 目录加载共享库?