2

Display first N natural numbers, the divisors of which are only 2, 3 and 7. I wrote something like that. I am a beginner in Lisp. Thank you!

defvar x 1
(defun numbers(n)
    if(mod x 2 )
    (loop for x from 1 to n
    do(print x)
    )
)
print(numbers())
Will Ness
  • 70,110
  • 9
  • 98
  • 181
  • You should check your syntax. Your code is not valid lisp code, e.g. there are missing parenthesis around your if statement. Start with a loop which prints all numbers unto `N`. Then check which are divisible by 2 and print only them, then add 3 and 7. – Martin Buchmann Oct 05 '19 at 13:11
  • Alright, thank you, Martin! – Doc Humanity Oct 05 '19 at 15:14
  • On the syntax: using some kind of IDE for Lisp is recommended. You can check out https://portacle.github.io/ (Emacs configured for Common Lisp development) which is as beginner friendly as you can get imo. – Thomas Houllier Oct 06 '19 at 08:04

1 Answers1

3

Because I just had some time, you could have a look at this. Might not be the perfect solution but should be a good starting point for a beginner. Check out the books in the info tab to get into the syntax etc.

(defun divisible-by (n m)
   "Returns T if N is evenly divisible by M."
   (zerop (mod n m)))

(defun numbers (n)
   "Print all number upto N which are divisible by 2, 3 and 7."
    (loop
       for i from 1 upto N
       if (and (divisible-by i 2) (divisible-by i 3) (divisible-by i 7))
         do (format t "~D~%" i)))
Martin Buchmann
  • 1,161
  • 7
  • 14
  • 1
    this is *O(n)*, but [*O(log^3 n)*](https://en.wikipedia.org/wiki/Regular_number#Number_theory) algorithm [exists](https://en.wikipedia.org/wiki/Regular_number#Algorithms) (so, near-exponentially better). you can find some imperative pseudocode e.g. at the top of [this answer](https://stackoverflow.com/a/10160054/849891). :) (I've re-tagged teh question). – Will Ness Oct 10 '19 at 11:15
  • 1
    also, the three divisibility tests can be replaced with one check for `gcd` with 42 being greater than 1. :) – Will Ness Oct 10 '19 at 11:28