📜  两个整数之间的最大互质集

📅  最后修改于: 2021-04-24 05:10:31             🧑  作者: Mango

给定两个表示范围的整数LR ,任务是在范围L到R中找到最大的互质数集。
例子:

方法:想法是从L迭代到R,并尝试将整数放置在集合中,以使集合的最大公因数保持为1。这可以通过存储集合的LCM以及每次添加元素之前来完成。进入集合,检查带有LCM的数字的GCD保持为1。最后,找到此类整数中最大的集合。

例如:

Let L = 10, R = 14

Element 10:
// Co-prime Sets 
S = {{10}},
LCM of Co-prime sets
A = {10}

Element 11:
// Element 11 can be added to
// the first set
S = {{10, 11}}
A = {110}

Element 12:
S = {{10, 11}, {12}}
A = {110, 12}

Element 13:
S = {{10, 11, 13}, {12}}
A = {1430, 12}

Element 14:
S = {{10, 11, 13}, {12}, {14}}
A = {1430, 12, 14}
Python
# Python implementation to find
# the largest co-prime set in a
# given range
  
import math 
  
# Function to find the largest
# co-prime set of the integers
def findCoPrime(n, m):
    # Initialize sets 
    # with starting integers
    a =[n]
    b =[[n]]
      
    # Iterate over all the possible
    # values of the integers
    for i in range(n + 1, m + 1):
      
        # lcm of each list in array 
        # 'b' stored in list 'a' 
        # so go through list 'a'
        for j in range(len(a)):
              
            # if there gcd is 1 then 
            # element add in that 
            # list corresponding to b
            if math.gcd(i, a[j])== 1:
                  
                # update the new lcm value
                q =(i * a[j])//math.gcd(i, a[j])
                r = b[j]
                r.append(i)
                b[j]= r
                a[j]= q
        else:
            a.append(i)
            b.append([i])
    maxi = []
    for i in b:
        if len(i) > len(maxi):
            maxi = i
    print(*maxi)
      
# Driver Code
if __name__ == "__main__":
    n = 10
    m = 14
    findCoPrime(n, m)


输出:
10 11 13