Skip to content

Instantly share code, notes, and snippets.

@ashmoran
Created January 6, 2011 23:12
Show Gist options
  • Select an option

  • Save ashmoran/768813 to your computer and use it in GitHub Desktop.

Select an option

Save ashmoran/768813 to your computer and use it in GitHub Desktop.
SICP exercise 1.22 - A surprising performance discovery
; Slow! The (next) "optimisation" slows it down
(define (find-divisor n test-divisor)
(define (next n)
(if (= n 2)
3
(+ n 2)))
(cond ((> (square test-divisor) n) n)
((divides? test-divisor n) test-divisor)
(else (find-divisor n (next test-divisor)))))
; Fast! Approx 1.6x as fast as when testing every possible divisor
(define (next n)
(if (= n 2)
3
(+ n 2)))
(define (find-divisor n test-divisor)
(cond ((> (square test-divisor) n) n)
((divides? test-divisor n) test-divisor)
(else (find-divisor n (next test-divisor)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment