gpt4 book ai didi

c++ - 带有嵌套循环的 C++ 程序的 Common Lisp 代码

转载 作者:太空狗 更新时间:2023-10-29 20:01:56 25 4
gpt4 key购买 nike

我是 Common Lisp 的初学者,但在 C++ 中不是这样。我试图在 CL 中镜像一个简单的 C++ 程序(参见 Pollard's Rho algorithm variant example in C++).C++程序运行没有错误。一个要求是两个程序的所有输出必须匹配。

C++版本

int gcd(int a, int b) {
int remainder;
while (b != 0) {
remainder = a % b;
a = b;
b = remainder;
}
return a;
}

int prime () {
int n = 10403, x_fixed = 2, cycle_size = 2, x = 2, factor = 1;

while (factor == 1) {
for (int count=1;count <= cycle_size && factor <= 1;count++) {
x = (x*x+1)%n;
factor = gcd(x - x_fixed, n);
}

cycle_size *= 2;
x_fixed = x;
}
cout << "\nThe factor is " << factor;
return 0;
}

Common Lisp 版本

这是我想出的。调试让我做噩梦,但我尝试了很多次并遍历了整个代码,但我仍然不知道我哪里出错了:(

(defun prime () 
(setq n 10403)
(setq x_fixed 2)
(setq cycle_size 2)
(setq x 2)
(setq factor 1)
(setq count 1)
(while_loop))

(defun while_loop ()
(print
(cond ((= factor 1)
(for_loop)
(setf cycle_size (* cycle_size 2))
(setf x_fixed x)
(setf count 1)
(while_loop))

((/= factor 1) "The factor is : ")))
(print factor))

(defun for_loop ()
(cond ((and (<= count cycle_size) (<= factor 1))
(setf x (rem (* x (+ x 1)) n))
(setf factor (gcd (- x x_fixed) n)))
((or (<= count cycle_size) (<= factor 1))
(setf count (+ count 1)) (for_loop))))

注意事项

  • 我将所有变量和常量命名为与 C++ 版本中相同的名称。
  • 我花了半天时间来决定要不要问这个问题
  • 如果我的 Common Lisp 代码看起来有趣或愚蠢,你可以不帮忙

最佳答案

您需要定义局部变量。

C 代码的基本翻译看起来类似于:

(defun my-gcd (a b)
(let ((remainder 0))
(loop while (/= b 0) do
(setf remainder (mod a b)
a b
b remainder))
a))

或使用类型声明:

(defun my-gcd (a b)
(declare (integer a b))
(let ((remainder 0))
(declare (integer remainder))
(loop while (/= b 0) do
(setf remainder (mod a b)
a b
b remainder))
a))

Common Lisp 中的 integer 数据类型是无界的——与 C++ 中的 int 不同。

关于c++ - 带有嵌套循环的 C++ 程序的 Common Lisp 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49354739/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com