Generating sorted list of all possible coprimes

前端 未结 4 1019
走了就别回头了
走了就别回头了 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:47

    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 of pair's elements; and if two sums are equal, then by the pair's first element.

    So, we generate ascending pairs of sum and first element, and keep only the coprimes. Easy cheesy!

    [ (first, second)
    | sum <- [3..]
    , first <- [2..sum `div` 2]
    , let second = sum-first
    , gcd first second == 1
    ]
    

提交回复
热议问题