a function that returns a list containing all prime numbers below n

Asked 1 years ago, Updated 1 years ago, 208 views

Using the Scheme language, we write a code that gives prime numbers up to n and lists them in ascending order.(You will also need to use cond and cons)

Example) Print 2, 3, 5, 7 when given 10

I think the code for checking prime numbers probably works, but the code for ascending order doesn't work.
If anyone has a good idea, I would appreciate it if you could share it with me.
Thank you for your cooperation.

My own code

 (define(prime n)
    (cond(
       (if(<n2))
       (if(=n2)2)
       (else(=isPrime checkPrime(n,2)))
          (if(isPrime)(prime(-n1))
          (else(prime(-n1))))))

(define(checkPrimeni))
   (cond(
      (if(=in)#t)
      (if(=(moduloni)0)#f)
      (else(checkPrime(n, (+n1))))))

scheme

2022-10-15 09:42

1 Answers

There are many methods, but the simple and efficient method is known as the Eratosthenes sieve. Since we look for prime numbers in order from the smallest values, we just need to check if they are broken by the prime numbers that have already been found. (Give only 2 as the first known prime.) Also, add the newly found prime to the list of results using cons. Adding results at the beginning of a linear list is a low cost, so accumulating results in this way is a common idiom in Scheme (LISP languages including ).

However, adding results to the beginning of the list is the reverse order found, so I will reverse the list with reverse.

Based on the above, the code is as follows. (Actually, the square root of n is sufficient to try splitting, but it is omitted for ease of splitting procedures. Also, although R5RS is assumed here, the Scheme specification has been revised and there are some incompatibilities, so it may not work depending on the version you expect.)

 (define(divide?n1n2)
  (zero?(modulon1n2)))

(define(divide-any?nls)
  (do(lsls(cdrls)))
      ((or(null?ls)
           (divide?n(carls)))
       (not(eqv?'()ls)))

(define (primes-less-than n)
  (let loop((result'(2)))
             (i 3)
    (cond((>=in)(reverse result))
          (else(loop)
                 (if(divide-any?ir result) result(consult))
                 (+i2))))

;; Test case. return a prime number less than or equal to 100
(write (primes-less-than 100))


2022-10-15 09:42

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.