2016-01-24 67 views
-1

我试图编写一个lisp函数来测试一个数是否为素数。我收到了lambda表达式错误(我已经搜索过以前回答过的与此有关的问题),但我找不到解决方案。代码错误Lambda表达式

(defun prime(n) 
( 
    (defvar '(*ok* nil) (*i* nil) (*d* nil) 
    (setf *ok* 1) 
    (loop for *i* from 1 to (sqrt n) do 
     ( 
    (if (= (mod n *d*) 0) 
      (setf *ok* 0)) 
     ) 
    ) 
    (if (= *ok* 1) 
      (format t "Numarul prim") 
      (format t "Numarul nu este prim") 
     ) 
) 

+4

这里是一个很好的Lisp介绍书。免费下载PDF文件: https://www.cs.cmu.edu/~dst/LispBook/ –

回答

5

我的意思并不是听起来粗鲁,但你需要读取一个体面的Common Lisp教程;你的代码更像是“你可以用任何语言编写C”,与一些“我没有得到动态可变填充”抛出。

要告诉你真正想要的,这里是我会怎么写你的逻辑:

(defun prime (n) 
    (if (loop 
     for i from 2 to (sqrt n) 
     when (zerop (mod n i)) return nil 
     finally (return t)) 
     "Numarul prim" 
     "Numarul nu este prim")) 

测试:

CL-USER> (loop 
    for i from 2 to 20 
    do (format t "~a ~a~%" i (prime i))) 
2 Numarul prim 
3 Numarul prim 
4 Numarul nu este prim 
5 Numarul prim 
6 Numarul nu este prim 
7 Numarul prim 
8 Numarul nu este prim 
9 Numarul nu este prim 
10 Numarul nu este prim 
11 Numarul prim 
12 Numarul nu este prim 
13 Numarul prim 
14 Numarul nu este prim 
15 Numarul nu este prim 
16 Numarul nu este prim 
17 Numarul prim 
18 Numarul nu este prim 
19 Numarul prim 
20 Numarul nu este prim 
NIL 

编辑1 - 使用局部变量:

(defun prime (n) 
    (let ((is-prime t)) 
    (loop 
     for i from 2 to (sqrt n) 
     when (zerop (mod n i)) 
     do (setf is-prime nil)) 
    (if is-prime 
     "Numarul prim" 
     "Numarul nu este prim"))) 

EDIT 2 - “我怎么能概括所有这些素数”

让我们回到一个真正的功能 - 在这种情况下,断言表示一个数是素数(返回t)或未被(返回nil):

(defun prime (n) 
    (loop 
    for i from 2 to (sqrt n) 
    when (zerop (mod n i)) return nil 
    finally (return t))) 

CL-USER> (prime 2) 
T 
CL-USER> (prime 3) 
T 
CL-USER> (prime 4) 
NIL 

和收集较低和上界之间的所有素数成列表的第二函数:

(defun primes (pfrom pto) 
    (loop 
    for i from pfrom to pto 
    when (prime i) collect i)) 

CL-USER> (primes 2 20) 
(2 3 5 7 11 13 17 19) 

,那么你只需要

CL-USER> (reduce '+ (primes 2 20)) 
77 
+0

好的。谢谢你的答案,但我需要做的像c风格算法没有制动程序时,你只要找到一个分频器,还需要包括如果测试在节目结束,但我不明白在lisp – JGF1994

+1

在C你会也从断路器IIRC中断开。我根据你的描述添加了一个版本,但我不会那样做。 – uselpa

+0

我怎么能summ所有这些素数的总和? – JGF1994