Add primes module skeleton.
This commit is contained in:
parent
87cff0a8c8
commit
d92ef2124c
1 changed files with 85 additions and 0 deletions
85
primes.scm
Normal file
85
primes.scm
Normal file
|
@ -0,0 +1,85 @@
|
|||
;;
|
||||
;; primes.scm
|
||||
;;
|
||||
;; Simple handling of 4-digit primes.
|
||||
;;
|
||||
;; ISC License
|
||||
;;
|
||||
;; Copyright 2023 Brmlab, z.s.
|
||||
;; Dominik Pantůček <dominik.pantucek@trustica.cz>
|
||||
;;
|
||||
;; Permission to use, copy, modify, and/or distribute this software
|
||||
;; for any purpose with or without fee is hereby granted, provided
|
||||
;; that the above copyright notice and this permission notice appear
|
||||
;; in all copies.
|
||||
;;
|
||||
;; THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
|
||||
;; WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
|
||||
;; WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
|
||||
;; AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
|
||||
;; CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
|
||||
;; OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
|
||||
;; NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
|
||||
;; CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
;;
|
||||
|
||||
(declare (unit primes))
|
||||
|
||||
(module
|
||||
primes
|
||||
(primes-tests!)
|
||||
|
||||
(import scheme
|
||||
(chicken base)
|
||||
testing)
|
||||
|
||||
;; Checks whether given number is prime by checking the remainder of
|
||||
;; the division by all primes less than square root of the number in
|
||||
;; question.
|
||||
(define (check-prime primes n)
|
||||
(let ((prime-at-most
|
||||
(inexact->exact
|
||||
(floor
|
||||
(sqrt n)))))
|
||||
(let loop ((ps primes))
|
||||
(if (null? ps)
|
||||
#t
|
||||
(let ((cp (car ps)))
|
||||
(if (<= cp prime-at-most)
|
||||
(if (eq? (remainder n cp) 0)
|
||||
#f
|
||||
(loop (cdr ps)))
|
||||
#t))))))
|
||||
|
||||
;; Generates list of primes less than given argument.
|
||||
(define (gen-primes less-than)
|
||||
(let loop ((primes '(2))
|
||||
(number 3))
|
||||
(if (< number less-than)
|
||||
(loop (if (check-prime primes number)
|
||||
(append primes (list number))
|
||||
primes)
|
||||
(+ number 2))
|
||||
primes)))
|
||||
|
||||
;; Used for checking any primes < 10000
|
||||
(define primes<100 (gen-primes 100))
|
||||
|
||||
;; Check whether given number is four-digit number and whether it is
|
||||
;; also prime.
|
||||
(define (is-4digit-prime? n)
|
||||
(and (>= n 1000)
|
||||
(<= n 9999)
|
||||
(check-prime primes<100 n)))
|
||||
|
||||
;; Module self-tests.
|
||||
(define (primes-tests!)
|
||||
(run-tests
|
||||
primes
|
||||
))
|
||||
|
||||
)
|
||||
|
||||
(import primes)
|
||||
|
||||
(primes-tests!)
|
Loading…
Add table
Add a link
Reference in a new issue