给定段中的互质对数

时间:2014-11-06 17:01:09

标签: number-theory

我正在寻找一种有效的算法,给出两个正整数nm,找到互质对(x,y)的数量,1 <= x <= n1 <= y <= m }。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

为什么不使用三元树来生成互质?像

这样的东西
def gen_coprimes(max_m, max_n):
    t1 = [(2,1)]
    t2 = [(3,1)]
    b1 = lambda m,n:(2*m-n, m)
    b2 = lambda m,n:(2*m+n, m)
    b3 = lambda m,n:(m+2*n, n)
    while t1 or t2:
        yield from t1
        yield from t2
        t1 = [(i,j) for i,j in (f(m,n) for m,n in t1 for f in (b1,b2,b3)) if i<max_m and j<max_n]
        t2 = [(i,j) for i,j in (f(m,n) for m,n in t2 for f in (b1,b2,b3)) if i<max_m and j<max_n]

list(gen_coprimes(5,6))提供[(2, 1), (3, 1), (3, 2), (4, 1), (4, 3)]

应该在O(n)附近。如果我错了,请纠正我,仍然可以处理这个重要的O符号。算法来自:http://en.wikipedia.org/wiki/Coprime_integers#Generating_all_coprime_pairs