shorter factor (issue #751 cont.)

This commit is contained in:
Roger Crew 2021-06-30 00:29:54 -07:00
parent 2759aaa306
commit 3337049811
2 changed files with 5 additions and 26 deletions

View file

@ -237,31 +237,10 @@
;;> Returns the factorization of \var{n} as a monotonically ;;> Returns the factorization of \var{n} as a monotonically
;;> increasing list of primes. ;;> increasing list of primes.
(define (factor n) (define factor
(when (zero? n) (let ((rfactor (make-factorizer '()
(error "cannot factor 0")) (lambda (l p k) (cons (make-list k p) l)))))
(factor-twos (lambda (n) (concatenate! (reverse (rfactor n))))))
n
(lambda (b n)
(let lp ((i 3) (ii 9) (n (abs n))
(res (append (make-list b 2)
(if (negative? n) (list -1) '()))))
(cond
((> ii n)
(reverse (if (= n 1) res (cons n res))))
((zero? (remainder n i))
(lp i ii (quotient n i) (cons i res)))
(else
(lp (+ i 2)
(+ ii (* (+ i 1) 4))
n
res)))))))
;; this version is slightly slower
;;(define factor
;; (let ((rfactor (make-factorizer '()
;; (lambda (l p k) (cons (make-list k p) l)))))
;; (lambda (n) (apply append! (reverse (rfactor n))))))
;;> The Euler totient φ(\var{n}) is the number of positive ;;> The Euler totient φ(\var{n}) is the number of positive
;;> integers less than or equal to \var{n} that are ;;> integers less than or equal to \var{n} that are

View file

@ -1,6 +1,6 @@
(define-library (chibi math prime) (define-library (chibi math prime)
(import (scheme base) (scheme inexact) (chibi optional) (srfi 27)) (import (scheme base) (scheme inexact) (chibi optional) (srfi 1) (srfi 27))
(cond-expand (cond-expand
((library (srfi 151)) (import (srfi 151))) ((library (srfi 151)) (import (srfi 151)))
((library (srfi 33)) (import (srfi 33))) ((library (srfi 33)) (import (srfi 33)))