algorithm - Find the smallest equally divisible in a range of numbers in Python, puzzle -


i'm trying solve projecteuler puzzle detailed below. current function works numbers 1 10, when try 1 20 loops forever without result.

2520 smallest number can divided each of numbers 1 10 without remainder. smallest positive number evenly divisible of numbers 1 20?

def calculate():     results = dict()     target = 20     num_to_test = 1     while len(results) < target:         j in range(1, target+1):             results[num_to_test] = true             if num_to_test % j != 0:                 # current num_to_test failed in 1-10, move on                 del results[num_to_test]                 break          num_to_test += 1     return min(results) 

can see issues in logic, , i'd know why working target of 10, not 20. thanks

your algorithm pretty inefficient, core of problem results dictionary accumulating 1 value each integer that's evenly divisible numbers 1-20, , while loop trying keep going until has 20 such numbers.

this 1 correct way implement inefficient algorithm:

def calculate():     target = 20     candidate = 1     success = false     divisors = range(1, target+1)     while not success:         divisor in divisors:             if candidate % divisor != 0:                 candidate += 1                 break         else:             success = true      return candidate 

note else clause on loop, not if. tutorial on flow control:

loop statements may have else clause; executed when loop terminates through exhaustion of list (with for) or when condition becomes false (with while), not when loop terminated break statement.

a more concise expression be:

candidate = 0 while not success:     candidate += 1     success = all((candidate % divisor == 0 divisor in divisors)) 

that uses generator expression all can short-circuit , avoid doing unnecessary calculation.

since puzzle i'll pass on suggesting better algorithms.


Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

VBA function to include CDATA -