From 1ab7d12b21f72f8ca7980718657499cf9eb4c3e2 Mon Sep 17 00:00:00 2001 From: Alex Shinn Date: Tue, 10 Jun 2014 20:07:49 +0900 Subject: [PATCH] Exposing the body of perfect? as aliquot. --- lib/chibi/math/prime.scm | 16 ++++++++++------ lib/chibi/math/prime.sld | 3 ++- tests/prime-tests.scm | 2 ++ 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/lib/chibi/math/prime.scm b/lib/chibi/math/prime.scm index a5d70a39..701d1ef7 100644 --- a/lib/chibi/math/prime.scm +++ b/lib/chibi/math/prime.scm @@ -205,15 +205,19 @@ ((= 1 (gcd n i)) (lp (+ i 1) (+ count 1))) (else (lp (+ i 1) count)))))) +;;> The aliquot sum s(n), equal to the sum of proper divisors of an +;;> integer n. +(define (aliquot n) + (let ((limit (+ 1 (quotient n 2)))) + (let lp ((i 2) (sum 1)) + (cond ((> i limit) sum) + ((zero? (remainder n i)) (lp (+ i 1) (+ sum i))) + (else (lp (+ i 1) sum)))))) + ;;> Returns true iff \var{n} is a perfect number, i.e. the sum of its ;;> divisors other than itself equals itself. (define (perfect? n) - (and (> n 1) - (let ((limit (+ 1 (quotient n 2)))) - (let lp ((i 2) (sum 1)) - (cond ((> i limit) (= n sum)) - ((zero? (remainder n i)) (lp (+ i 1) (+ sum i))) - (else (lp (+ i 1) sum))))))) + (and (> n 1) (= n (aliquot n)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Random prime generation diff --git a/lib/chibi/math/prime.sld b/lib/chibi/math/prime.sld index 1ee9ea45..61474975 100644 --- a/lib/chibi/math/prime.sld +++ b/lib/chibi/math/prime.sld @@ -1,7 +1,8 @@ (define-library (chibi math prime) (import (scheme base) (scheme inexact) (srfi 27) (srfi 33)) - (export prime? nth-prime prime-above prime-below factor perfect? totient + (export prime? nth-prime prime-above prime-below factor perfect? + totient aliquot provable-prime? probable-prime? random-prime random-prime-distinct-from coprime? random-coprime modular-inverse modular-expt diff --git a/tests/prime-tests.scm b/tests/prime-tests.scm index 7f3eb66d..540c3ab0 100644 --- a/tests/prime-tests.scm +++ b/tests/prime-tests.scm @@ -70,6 +70,8 @@ (test '(2 2 3) (factor 12)) (test '(3 3 3 5 7) (factor 945)) +(test 975 (aliquot 945)) + (do ((i 3 (+ i 2))) ((>= i 101)) (test (number->string i) (prime? i)