Skip to content

Commit

Permalink
Add sample prime factors.
Browse files Browse the repository at this point in the history
  • Loading branch information
codecop committed Aug 4, 2023
1 parent 7723edf commit 24746fd
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .github/workflows/ci-workflow-gambit.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,6 @@ jobs:

- name: Test the example
run: gsi.exe sample\sample-unit-test.scm

- name: Test the prime factors
run: gsi.exe sample\prime-factors-test.scm
23 changes: 23 additions & 0 deletions sample/prime-factors-test.scm
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
(include "prime-factors.scm")
(include "../assert-r5rs.scm")

(test-case "one"
(assert-null (prime-factors 1)))

(test-case "two"
(assert-number-list= (list 2) (prime-factors 2)))

(test-case "three"
(assert-number-list= (list 3) (prime-factors 3)))

(test-case "four"
(assert-number-list= (list 2 2) (prime-factors 4)))

(test-case "eight"
(assert-number-list= (list 2 2 2) (prime-factors 8)))

(test-case "nine"
(assert-number-list= (list 3 3) (prime-factors 9)))

(test-case "max"
(assert-number-list= (list 2147483647) (prime-factors 2147483647)))
26 changes: 26 additions & 0 deletions sample/prime-factors.scm
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
(define (prime-factors n)
(test-candidate n 2))

(define (test-candidate n candidate)
(cond
((= n 1) (list))
((too-large? n candidate) (prime n))
((divides? n candidate) (keep-candidate n candidate))
(else (next-candidate n candidate))))

(define (too-large? n candidate)
(> candidate (sqrt n)))

(define (prime n)
(list n))

(define (divides? n candidate)
(= (modulo n candidate) 0))

(define (keep-candidate n candidate)
(append
(prime candidate)
(test-candidate (/ n candidate) candidate)))

(define (next-candidate n candidate)
(test-candidate n (+ candidate 1)))

0 comments on commit 24746fd

Please sign in to comment.