Ad
  • Custom User Avatar

    I mean you need up to sqrt(n)+1 no n/2+1

  • Custom User Avatar

    No, try the previous algorithm. It will time out.

    The logic behind this is to greatly reduce numbers looped, sometimes up to one fourth, especially on large numbers. When I get a divisor I get its complement. When I reach a number that is already in the list, I know that I have already reached the second side of divisors, thus I have got everything. I can get out of the loop after that. For example, let's see how 12 is processed:

    divisors(12)
    # iteration 1
    [1,12] # identifies 1 as divisor and then gets the complement of it to 12, which is 12. The largest divisor is half of that one, so we can break out of the loop halfway through anyway
    # iteration 2
    [1,12,2,6]
    # iteration 3
    [1,12,2,6,3,4]
    #iteration 4
    break # because I have ran into a number already in the divisors list, that means I have got all the divisors and all the complements.
    
    

    Actually I can optimize it further by using fromkeys

  • Custom User Avatar

    You are looping over much more integers than needed

  • Custom User Avatar

    Please check the fork; the fork can view over less than one half.

    But your algorithm is still great!

  • Custom User Avatar

    Both algorithms are linear on the input; but yes, this one is faster

  • Custom User Avatar

    I think that no number has a divisor larger than it's half other than itself too .

  • Default User Avatar

    This program works faster because it doesn't go through the entire range, you only need to view half of it