简体   繁体   English

Lisp中的质数检查

[英]Prime number check in Lisp

Can someone point out my mistake here.有人可以在这里指出我的错误。 I am trying to check if a number is a prime number or not.我正在尝试检查一个数字是否是质数。 It works to an extent but I have a semantics error.它在一定程度上有效,但我有一个语义错误。 For example it is telling me that 9 is a prime number but at the same time it is telling me 4 and 6 are not prime numbers and I am confused.例如,它告诉我 9 是质数,但同时它告诉我 4 和 6 不是质数,我很困惑。

(defvar *prime* nil)

(defun primeCheck (x y)
    (if (and (>= x y) (not (= (mod x y) 0))) 
        (progn 
            (setf y (+ y 1))
            (primeCheck x y)
            (setf *prime* 'yes))
    (setf *prime* 'no))
)
(primeCheck 9 2)
(if  (equal *prime* 'yes) (print "Number is prime") (print "Number is not prime"))

I suggest you to download some IDE (for example LispWorks Personal Edition) or find online REPL for Common Lisp and run your codes in it.我建议您下载一些 IDE(例如 LispWorks 个人版)或查找 Common Lisp 的在线 REPL 并在其中运行您的代码。 Your mistakes:你的错误:

  • ("prime number") is badly formed list. ("prime number")是格式错误的列表。 Replace that with (print "prime number")将其替换为(print "prime number")
  • primeCheck calls some (yet) undefined function modulus primeCheck调用一些(尚未)未定义的 function modulus
  • (*prime-Check* nil) is badly formed list. (*prime-Check* nil)是格式错误的列表。 Replace with (setf *prime-Check* nil)替换为(setf *prime-Check* nil)
  • badly formed cond and and不良形成的cond and
  • with all these corrections, it doesn't work for 2,3,5 etc.通过所有这些更正,它不适用于 2、3、5 等。

Many things are wrong.很多事情都是错的。

How about using primarity test eg from SICP (structure and interpretation of computer programs)?使用 SICP(计算机程序的结构和解释)中的素数测试怎么样?

;; from SICP (here in clojure)
;; http://www.sicpdistilled.com/section/1.2.6/

(defun smallest-divisor (n)
  (find-divisor n 2))

(defun square (n)
  (* n n))

(defun find-divisor (n test-divisor)
  (cond ((> (square test-divisor) n) n)
        ((dividesp test-divisor n) test-divisor)
        (t (find-divisor n (1+ test-divisor)))))

(defun dividesp (a b)
  (zerop (mod b a)))

(defun primep (n)
  (= n (smallest-divisor n)))

primep tests for primarity. primep测试素数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM