Skip to content

Instantly share code, notes, and snippets.

@MikeMKH
Created August 31, 2016 11:36
Show Gist options
  • Select an option

  • Save MikeMKH/9f6aa139ceaf5afb94a4cdfd7f81aeaa to your computer and use it in GitHub Desktop.

Select an option

Save MikeMKH/9f6aa139ceaf5afb94a4cdfd7f81aeaa to your computer and use it in GitHub Desktop.
Prime Factors kata in Racket using recursion
#lang racket
(require rackunit rackunit/text-ui)
(define (prime-factors n)
(define (factors result n value)
(cond
[(<= n 1) (reverse result)]
[(zero? (modulo n value)) (factors (cons value result) (/ n value) value)]
[else (factors result n (add1 value))]))
(factors '() n 2))
(run-tests
(test-suite
"prime factorization tests"
(test-case
"primes should only have themselves as factors"
(let ([primes '(2 3 5 7 11 13 17)])
(for-each
(lambda (n)
(check-equal? (prime-factors n) (list n) (~a "factors of " (~v n) " should be only " (~v n))))
primes)))
(test-case
"squaring primes should only have themselves as factors"
(let ([primes '(2 3 5 7 11 13 17)])
(for-each
(lambda (n)
(check-equal? (prime-factors (* n n)) (list n n) (~a "factors of " (~v (* n n)) " should be " (~v n) " twice")))
primes)))
(check-equal? (prime-factors (* 2 3 5 5)) '(2 3 5 5) "prime factors of 2 * 3 * 5 * 5 are those values")
(test-case
"factors should be in ascending order"
(let ([factors '(2 3 3 5 7 2)])
(check-equal? (sort factors <) (prime-factors (apply * factors)))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment