diff options
author | bd <bdunahu@operationnull.com> | 2024-08-05 14:06:25 -0600 |
---|---|---|
committer | bd <bdunahu@operationnull.com> | 2024-08-05 14:06:25 -0600 |
commit | 5e5f7eb2304b9f9f2a54c163cdd79720ea8e0892 (patch) | |
tree | c47251b040ac6f554387810686c3b9cf76e574db /circular-primes/cp.scm | |
parent | 3324327b80a50e94843dedbb704683ee9b3a9955 (diff) |
Circular primes implementation and tests
Diffstat (limited to 'circular-primes/cp.scm')
-rw-r--r-- | circular-primes/cp.scm | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/circular-primes/cp.scm b/circular-primes/cp.scm new file mode 100644 index 0000000..1f4105c --- /dev/null +++ b/circular-primes/cp.scm @@ -0,0 +1,41 @@ +(define-module (cp) + #:use-module (soe) + #:use-module (srfi srfi-1) + #:export (generate-circular-primes-to + number->circular-list + list-rotate)) + + +(define (generate-circular-primes-to n) + "Returns the 'circular primes' under N." + (let loop ((primes (generate-primes-to n)) + (circular-primes '())) + (if (null? primes) + (sort circular-primes <) + (let* ((circle (number->circular-list (car primes))) + (prev-num-primes (length primes)) + (primes (lset-difference eqv? primes circle))) + (loop primes + ;; primes contains no duplicates, so: + (if (eq? (length primes) (- prev-num-primes (length circle))) + (append circle circular-primes) + circular-primes)))))) + +(define (number->circular-list n) + "Given number N, returns a list of all rotated +numbers of N, i.e.: + +123 -> '(312 231 123)" + (let ((lst (string->list (number->string n)))) + (let loop ((accum (list lst)) + (next (list-rotate lst))) + (if (equal? next lst) + (map (lambda (x) (string->number (list->string x))) + accum) + (loop (cons next accum) + (list-rotate next)))))) + +(define (list-rotate lst) + (if (null? lst) + '() + (append (cdr lst) (list (car lst))))) |