From d92ef2124ca767de0748082b41692405e8b95afd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Pant=C5=AF=C4=8Dek?= Date: Thu, 16 Mar 2023 22:24:24 +0100 Subject: [PATCH] Add primes module skeleton. --- primes.scm | 85 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 primes.scm diff --git a/primes.scm b/primes.scm new file mode 100644 index 0000000..d08f9b0 --- /dev/null +++ b/primes.scm @@ -0,0 +1,85 @@ +;; +;; primes.scm +;; +;; Simple handling of 4-digit primes. +;; +;; ISC License +;; +;; Copyright 2023 Brmlab, z.s. +;; Dominik Pantůček +;; +;; 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!)