diff --git a/lib/chibi/math/prime-test.sld b/lib/chibi/math/prime-test.sld index d171be56..ba8dc82a 100644 --- a/lib/chibi/math/prime-test.sld +++ b/lib/chibi/math/prime-test.sld @@ -32,7 +32,19 @@ (test 1009 (nth-prime 168)) (test 1013 (nth-prime 169)) + (test 2 (prime-above 1)) + (test 3 (prime-above 2)) + (test 5 (prime-above 3)) + (test 5 (prime-above 4)) + (test 7 (prime-above 5)) (test 907 (prime-above 888)) + (test 911 (prime-above 907)) + (test-not (prime-below 2)) + (test 2 (prime-below 3)) + (test 3 (prime-below 4)) + (test 3 (prime-below 5)) + (test 5 (prime-below 6)) + (test 5 (prime-below 7)) (test 797 (prime-below 808)) (test 1 (totient 2)) diff --git a/lib/chibi/math/prime.scm b/lib/chibi/math/prime.scm index 65ba56e3..50775b40 100644 --- a/lib/chibi/math/prime.scm +++ b/lib/chibi/math/prime.scm @@ -146,20 +146,34 @@ ;;> Returns the first prime less than or equal to \var{n}, or #f if ;;> there are no such primes. (define (prime-below n) - (and (>= n 3) - (let lp ((n (if (even? n) (- n 1) n))) - (if (prime? n) n (lp (- n 2)))))) + (cond + ((> n 3) + (let lp ((n (if (even? n) (- n 1) (- n 2)))) + (if (prime? n) n (lp (- n 2))))) + ((= n 3) + 2) + (else + #f))) ;;> Returns the first prime greater than or equal to \var{n}. If the ;;> optional \var{limit} is given and not false, returns \scheme{#f} ;;> if no such primes exist below \var{limit}. (define (prime-above n . o) (let ((limit (and (pair? o) (car o)))) - (let lp ((n (if (even? n) (+ n 1) n))) - (cond - ((and limit (>= n limit)) #f) - ((prime? n) n) - (else (lp (+ n 2))))))) + (cond + ((< n 2) + 2) + (limit + (let lp ((n (if (even? n) (+ n 1) (+ n 2)))) + (cond + ((>= n limit) #f) + ((prime? n) n) + (else (lp (+ n 2)))))) + (else + (let lp ((n (if (even? n) (+ n 1) (+ n 2)))) + (cond + ((prime? n) n) + (else (lp (+ n 2))))))))) ;;> Returns the factorization of \var{n} as a monotonically ;;> increasing list of primes.