U
U
Umid2017-07-29 10:21:57
Python
Umid, 2017-07-29 10:21:57

How to optimize the algorithm to perform the 5 task from the Euler project?

Good afternoon!
Wrote an algorithm to implement this task .

def euler5(limit):
  hasNumberFound = False
  iterator = 1

  while not hasNumberFound:
    num = limit * iterator

    for divider in range(2, limit):
      if num % divider != 0:
        break
    else: 
      hasNumberFound = True
      return num
    iterator += 1

print( euler5(20) )

The confusing thing is that it takes 13.5 seconds to complete the task with the value of the function argument equal to 20. The output is: 232792560.
Is it possible to optimize the algorithm?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2017-07-29
@DarCKoder

The problem can be solved without brute force.
To begin with, take all the numbers from 2 to 20 and decompose into prime factors.
3 = 31
4 = 22
5 = 51
6 = 21·31
7 = 71
8 = 23
9 = 32
10 = 21·51
11 = 111
12 = 22·31
13 = 131
14 = 21·71
15 = 31·51
16 = 24
17 = 171
18 = 21·32
19 = 191
20 = 22·51

Then you take the maximum powers from all expansions and multiply them:
2 4 3 2 5 1 7 1 11 1 13 1 17 1 19 1 = 232792560

A
Andrey Shatokhin, 2017-07-29
@Sovigod

So why are you iterating over an iterator over 1?
Find all prime numbers <= limit and multiply. Increment the iterator by this product.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question