Add exercise 4.36 Pythagorean triples

This commit is contained in:
Oliver Payne 2023-10-24 23:01:27 +01:00
parent 5002cfe4aa
commit 0e99db8285
2 changed files with 24 additions and 2 deletions

View File

@ -28,8 +28,29 @@
;; To generate all pythagorean triples, it is not sufficient to
;; replace an-integer-between with an-integer-starting-from because
;; this would attempt to search through all i, then all j and then all
;; k. As such, we'd never get to the second value of j or k.
;; this would attempt to search through all k, then all j and then all
;; i. As such, we'd never get to the second value of j or i.
;; Instead, we need to visit the values of i, j and k diagonally to
;; ensure that they are visited in order.
(define (a-pythagorean-triple)
(let ((t (a-triple-with-sum-from 3)))
(let ((i (car t))
(j (car (cdr t)))
(k (car (cdr (cdr t)))))
(require (= (+ (* i i) (* j j))
(* k k)))
(list i j k))))
(define (a-triple-with-sum-between low high)
(let ((i (an-integer-between 1 high)))
(let ((j (an-integer-between i (max 1 (- high i)))))
(let ((k (an-integer-between j (max 1 (- high j i)))))
(let ((sum (+ i j k)))
(require (>= sum low))
(require (< sum high))
(list i j k))))))
(define (a-triple-with-sum-from n)
(amb (a-triple-with-sum-between n (+ n 1))
(a-triple-with-sum-from (+ n 1))))

View File

@ -177,6 +177,7 @@
(list '>= >=)
(list '<= <=)
(list 'abs abs)
(list 'max max)
(list 'remainder remainder)
(list 'integer? integer?)
(list 'sqrt sqrt)