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

后端 未结 6 781
花落未央
花落未央 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:50

    hi all read code and comments carefully you can easily understand

    def amicable_number(number):
    
        list_of_tuples=[] 
        amicable_pair=[] 
    
        for i in range(2,number+1): # in which range you want to find amicable
    
            divisors = 1 # initialize the divisor
    
            sum_of_divisors=0 #here we add the divisors
    
            while divisors < i: # here we take one number and add their divisors
    
                if i%divisors ==0:   #checking condition of complete divison
                    sum_of_divisors += divisors
                divisors += 1
            list_of_tuples.append((i,sum_of_divisors)) #append that value and sum of there divisors
    
        for i in list_of_tuples: 
                                  #with the help of these loops we find amicable with duplicacy
            for j in list_of_tuples:
                if i[0] == j[1] and i[1] == j[0] and j[0] != j[1]: #condition of amicable number 
    
                    amicable_pair.append((j[0],i[0])) # append the amicable pair
    
        # i write this for_loop for removing the duplicacy if i will mot use this for loop this
        # be print both (x,y) and (y,x) but we need only one among them
        for i in amicable_pair:
    
            for j in amicable_pair[1:len(amicable_pair)]: #subscript the list
                if i[0] == j[1]:
                    amicable_pair.remove(i) # remove the duplicacy
    
        print('list of amicable pairs number are: \n',amicable_pair)
    
    amicable_number(284) #call the function
    

提交回复
热议问题