Generating sorted list of all possible coprimes

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

    As @Bakuriu suggests, merging an infinite list of infinite lists is a solution, but the devil is in the details.

    The diagonal function from the universe-base package can do this, so you could write:

    import Data.Universe.Helpers
    
    coprimes = diagonal [ go n | n <- [2..] ]
      where go n = [ (n,k) | k <- [n+1..], gcd n k == 1 ]
    

    Note - this doesn't satisfy your sorted criteria, but I mention it because the functions in that package are useful to know about, and implementing a function like diagonal correctly is not easy.

    If you want to write your own, consider decomposing the infinite grid N x N (where N is the natural numbers) into diagonals:

    [ (1,1) ] ++ [ (1,2), (2,1) ] ++ [ (1,3), (2,2), (3,1) ] ++ ...
    

    and filtering this list.

提交回复
热议问题