I need a function which lists smaller co-prime numbers of given number. For example, co(11) gives [1,7,9,10]
, sum of it gives me 27
. But i want to get co-prime numbers which generates maximum sum. For co(11) it should eliminate 10 (since 5+8 > 10) and return [1,5,7,8,9]
to get maximum sum which is 30
.
Here is the function:
import math
def Co(n):
Mylist = [x for x in range(1, n)]
removeds =[]
for x in Mylist:
y = Mylist.index(x)
for z in Mylist[y+1:]:
if math.gcd(x, z) != 1:
removed = Mylist.pop(y)
removeds.append(removed)
#print(removed)
Mylist[1:] = Mylist
#print(Mylist)
break
Mylist= list(dict.fromkeys(Mylist))
removeds = list(dict.fromkeys(removeds))
removeds.sort(reverse = True)
for a in removeds:
check = []
for b in Mylist:
if math.gcd(a, b) != 1:
break
else:
check.append(a)
if len(check) == len(Mylist):
Mylist.append(a)
print(Mylist)
print(sum(Mylist))
Co(11)
and result is:
[1, 7, 9, 10]
27
In order to get maximum sum of possible co-prime sets, it should return
[1, 5, 7, 8, 9]
30
I thought about getting all possible co-prime sets then compare them to get the maximum summed one. But when the Co(N)
gets bigger, it becomes uncontrollable and not efficient. I know this is more math problem than python but any hints would be appreciated.