What is the most efficient way to find amicable numbers in python?

后端 未结 6 769
花落未央
花落未央 2020-12-19 23:13

I\'ve written code in Python to calculate sum of amicable numbers below 10000:

def amicable(a, b):
   total = 0
   result = 0
   for i in range(1, a):
               


        
6条回答
  •  無奈伤痛
    2020-12-19 23:56

    Note that you don't need to have a double loop. Just loop M from 1 to 10000, factorize each M and calculate sum of divisors: S(M). Then check that N = S(M)-M has the same sum of divisors. This is a straight-forward algorithm derived from the definition of an amicable pair.

    There are a lot of further tricks to optimize amicable pairs search. It's possible to find all amicable numbers below 1,000,000,000 in just a fraction of a second. Read this in-depth article, you can also check reference C++ code from that article.

提交回复
热议问题