问题描述
我正在定义一个函数来测试数字是否为质数,并且我有一个有效的算法(在Python中),并且已将其大部分移植到Lisp。但是问题是我的素数测试即使不应该通过也一直通过。例如,isPrime(13)
仍会到达return NIL
,即使它应该不符合when
条件。
(defun isPrime(n)
(cond
((< n 2); numbers less than 2 aren't prime
NIL
)
((equal n 2); 2 is the only even prime
T
)
((equal (rem n 2) 0); Even numbers are never prime (besides 2)
NIL
)
((> n 2)
(loop for i from 2 to n do(
when(equal (rem n i) 0);If n is evenly divisible by i,we have found a factor other than 1 and n
(return NIL)
)
)
)
(t T); If we get through all that with no issue,the number is prime
)
)
问题:为什么我的函数无论如何都到达return NIL
分支?
此外,如果这只是测试素数的一种不好方法,是否还有一种类似Lisp的方法(不必担心性能,只担心算法的正确性和可读性。)
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)