Finding friendly couples with cycles
-
Set a programme for the task. The two natural numbers are called friendly if each is equal to the sum of all other (self different) is considered). For example, 220 (1+2+4+5+10+11+20+22+44+55+110=284) and 284 (1+2+4+71+142=220) friendly numbers. Couple needs to be Take one in the line, split the gaps. Find all the couples. Naturally friendly, less than 10,000.
The solutions to this task are already on the Internet, but as far as I can see, they're using the masses that I don't like. I'd like to do this only with cycles, like I did:
for i in range(1, 9999): for k in range(1, i // 2 + 1): if i % k == 0: sum1 += k for j in range(i + 1, 9999): if j == i: continue for k in range(1, j // 2 + 1): if j % k == 0: sum2 += k if sum1 == j and sum2 == i: print(i, j, sep=' ') sum1, sum2 = 0, 0
But the solution is so long that I don't want to wait for a second pair of numbers. Please help with optimization.
-
Is that a good decision?
def getSum(value): res = 1 for i in range(2, int(value**0.5) + 1): if value % i == 0: res += i + value // i return res
for i in range(10, 10000):
sum1 = getSum(i)
sum2 = getSum(sum1)
if sum2 == i and sum1 != sum2:
print(i, sum1)
The calculation of multipliers shall be carried out as soon as possible (sqrt(N) speed)
i.e. to find all businessmen don't have to go away.1
beforeN / 2
It's enough to get out of here.2 до sqrt(N)
Finding two businessmen, the main and the second, who are equal to the private number and the found parentNo specially issued number 28 (equal to the amount of proprietors)
Failure - there will be duplicates (no list solves this problem), i.e., will be found
220 284
and284 220
Use the function
sum
but then it's not clear that everyone uses the lists:for value in range(10, 10000):
sum1 = 1 + sum((i + value // i) for i in range(2, int(value0.5) + 1) if value % i == 0)
sum2 = 1 + sum((i + sum1 // i) for i in range(2, int(sum10.5) + 1) if sum1 % i == 0)
if sum2 == value and sum1 != sum2:
print(value, sum1)
P. S.
By the way, it's better to isolate the other squares, because the root of the algorithm above is doubled.
def getSum(value):
res = 1 + (0 if int(value**0.5)2 != value else int(value0.5))
for i in range(2, int(value ** 0.5)):
if value % i == 0:
res += i + value // i
return res
now.
25
instead of wrong11
issued correctly6