Generating sorted list of all possible coprimes

前端 未结 4 1024
走了就别回头了
走了就别回头了 2021-01-22 07:07

I need to generate infinite sorted list of all coprimes. The first element in each pair must be less than the second. The sorting must be done in ascending order -- by the sum o

4条回答
  •  遥遥无期
    2021-01-22 07:44

    While probably not the most optimal way it should works if you first generate all possible pairs and then filter them.

    So using your criteria:

    pairs :: [(Integer,Integer)]
    pairs = [ (i,l-i) | l <- [1..], i <- [1..l-1] ]
    
    coprimes :: [(Integer,Integer)]
    coprimes = [ (i,j) | (i,j) <- pairs, 1 < i, i < j,gcd i j == 1]
    

    produces

    λ> take 10 coprimes
    [(2,3),(2,5),(3,4),(3,5),(2,7),(4,5),(3,7),(2,9),(3,8),(4,7)]
    

    now of course you can put some of the stuff 1 < i and i < j comes to mind into the pairs definition or even join them but I think here it's more obvious what's going on

提交回复
热议问题