fork download
  1. ;; Generate Pythagorean triples using combinations. (1.03)
  2. ;; @see Yn3fZb
  3.  
  4. (use-modules (srfi srfi-1) ; pair-fold-right
  5. (srfi srfi-67) ; list-compare
  6. (ice-9 format)) ; advanced formatting
  7.  
  8. ;; Combinations.
  9.  
  10. (define (pair-map proc l)
  11. (pair-fold-right (lambda (item init)
  12. (cons (proc item) init))
  13. '() l))
  14.  
  15. (define (pair-append-map proc l)
  16. (apply append (pair-map proc l)))
  17.  
  18. (define (combinations sequence k)
  19. (if (zero? k)
  20. (list '())
  21. (pair-append-map (lambda (rest)
  22. (map (lambda (comb)
  23. (cons (car rest) comb))
  24. (combinations (cdr rest) (- k 1))))
  25. sequence)))
  26.  
  27. ;; Pythagorean triples.
  28.  
  29. (define (primitive-pythagorean-triple? x y z)
  30. (and (< x y z)
  31. (= (+ (* x x) (* y y)) (* z z))
  32. (= (gcd x y z) 1)))
  33.  
  34. (define (pythagorean-triples n)
  35. (filter-map (lambda (v)
  36. (apply (lambda (x y z)
  37. (if (primitive-pythagorean-triple? x y z)
  38. v
  39. #f))
  40. v))
  41. (combinations (iota n 1) 3)))
  42.  
  43. ;; Main.
  44.  
  45. (define (list-less-reverse x y)
  46. (< (list-compare (reverse x) (reverse y)) 0))
  47.  
  48. (for-each (lambda (v)
  49. (format #t "(~{~2D~^ ~})~%" v))
  50. (sort (pythagorean-triples 97) list-less-reverse))
Success #stdin #stdout 0.8s 35472KB
stdin
Standard input is empty
stdout
( 3  4  5)
( 5 12 13)
( 8 15 17)
( 7 24 25)
(20 21 29)
(12 35 37)
( 9 40 41)
(28 45 53)
(11 60 61)
(33 56 65)
(16 63 65)
(48 55 73)
(36 77 85)
(13 84 85)
(39 80 89)
(65 72 97)