P32 (**) Determine the greatest common divisor of two positive integer numbers.

来源:互联网 发布:超级卡司是真是假 知乎 编辑:程序博客网 时间:2024/06/11 11:01

问题描述

sash> (gcd 36 63)   -> 9

用欧几里得算法解决。

解法

最大公约数运算在数论上比较常见,标准库有同名的函数。
题目要求a和b是正数,下面的实现不能用于负数的情况。因

gcd(a,b)=gcd(a,b)

故只要简单处理一下参数就可以适用于负数的情况

(define gcd  (lambda (a b)    (if (zero? b)        a        (gcd b (floor-remainder a b)))))
1 0
原创粉丝点击