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

Common Lisp code for a C++ program with nested loops

我是 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))))

备注

你真的需要多读一些关于 Common Lisp 的书。它具有 C++ 的所有基本命令式结构,因此无需费力地翻译一个简单的算法。参见示例 Guy Steele's classic, available for free

这里有一个更合理和地道的trans-coding:

(defun prime-factor (n &optional (x 2))
  (let ((x-fixed x)
        (cycle-size 2)
        (factor 1))
    (loop while (= factor 1)
      do (loop for count from 1 to cycle-size
           while (<= factor 1)
           do (setq x (rem (1+ (* x x)) n)
                    factor (gcd (- x x-fixed) n)))
         (setq cycle-size (* 2 cycle-size)
               x-fixed x)))
    factor))

(defun test ()
  (prime-factor 10403))

您需要定义局部变量。

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 不同。