Closed. This question is off-topic. It is not currently accepting answers. Learn more。
想改进这个问题吗Update the question所以堆栈溢出的值小于aa>。
6年前关闭。
我刚开始学习普通的lisp,所以我一直在研究euler问题这是我的解决方案(在on-topic的帮助下)你们对风格的改变有什么建议吗?有什么建议可以使它更具口齿不清?
可以简化为:
我对您的代码的其他评论与其说是关于Lisp风格,不如说是关于算法创建所有这些中间的数字列表似乎是一个糟糕的方法,只需编写计算和测试数字的嵌套循环。
但是
下面是另一个优化:
使内部循环从
想改进这个问题吗Update the question所以堆栈溢出的值小于aa>。
6年前关闭。
我刚开始学习普通的lisp,所以我一直在研究euler问题这是我的解决方案(在on-topic的帮助下)你们对风格的改变有什么建议吗?有什么建议可以使它更具口齿不清?
; A palindromic number reads the same both ways. The largest palindrome made
; from the product of two 2-digit numbers is 9009 = 91 99.
; Find the largest palindrome made from the product of two 3-digit numbers.
(defun num-to-list (num)
(let ((result nil))
(do ((x num (truncate x 10)))
((= x 0 ) result)
(setq result (cons (mod x 10) result)))))
(defun palindrome? (num)
(let ((x (num-to-list num)))
(equal x (reverse x))))
(defun all-n-digit-nums (n)
(loop for i from (expt 10 (1- n)) to (1- (expt 10 n)) collect i))
(defun all-products-of-n-digit-nums (n)
(let ((nums (all-n-digit-nums n)))
(loop for x in nums
appending (loop for y in nums collecting (* x y)))))
(defun all-palindromes (n)
(let ((nums (all-products-of-n-digit-nums n)))
(loop for x in nums
when (palindrome? x) collecting x)))
(defun largest-palindrome (n)
(apply 'max (all-palindromes 3)))
(print (largest-palindrome 3))
最佳答案
(setq list (cons thing list))
可以简化为:
(push thing list)
我对您的代码的其他评论与其说是关于Lisp风格,不如说是关于算法创建所有这些中间的数字列表似乎是一个糟糕的方法,只需编写计算和测试数字的嵌套循环。
(defun all-palindromes (n)
(loop for i from (expt 10 (1- n)) to (1- (expt 10 n))
do (loop for j from (expt 10 (1- n)) to (1- (expt 10 n))
for num = (* i j)
when (palindrome? num)
collect num)))
但是
LOOP
有一个功能可以使用:MAXIMIZE
因此,您可以:(defun largest-palindrome (n)
(loop with start = (expt 10 (1- n))
and end = (1- (expt 10 n))
for i from start to end
do (loop for j from start to end
for num = (* i j)
when (palindrome? num)
maximize num)))
下面是另一个优化:
(defun largest-palindrome (n)
(loop with start = (expt 10 (1- n))
and end = (1- (expt 10 n))
for i from start to end
do (loop for j from i to end
for num = (* i j)
when (palindrome? num)
maximize num)))
使内部循环从
COLLECT
开始而不是从i
开始,避免了同时检查start
和M*N
的冗余。10-06 11:08