racket - scheme - Show all the pairs of elements which have the greatest common divisor 1 -
i started algortihm combinations when m become 0 in recursion, first y '(()) program show () repeat 4*the size of list times.
(define (pairs-gcd l) (define (comb m lst) (cond ((= m 0) '(())) ((null? lst) '()) (else (append (map (lambda (y) (cond (equal? (gcd(car lst) y) 1) (cons (car lst) y))) (comb (- m 1) (cdr lst))) (comb m (cdr lst)))))) (comb 2 l)
) edit: corrected output input: '(2 5 3 6 11 15) output: '((2 5) (2 3) (2 11) (2 15) (5 3) (5 6) (5 11) (6 11) (3 11) (6 11) (11 15))
this simple if use racket's built-in procedures - can generate 2-element combinations, test them given condition , output list correct pairs:
(define (pairs-gcd lst) (for/list ([pair (in-combinations lst 2)] #:when (= (apply gcd pair) 1)) pair))
for example:
(pairs-gcd '(2 5 3 6 11 15)) => '((2 5) (2 3) (5 3) (5 6) (2 11) (5 11) (3 11) (6 11) (2 15) (11 15))
Comments
Post a Comment