Project Euler Question 5 Answer

Project Euler Question 5 Answer

Project Euler Question 5 Answer

stats = False
counter = 1
while stats == False:
    iStat = False
    for i in [11, 13, 14, 16, 17, 18, 19, 20]: # for i in range(1, 20) we pull the unnecessarily numbers the rest are [11, 13, 14, 16, 17, 18, 19, 20]
        if counter % i == 0:
            iStat = True
        else:
            iStat = False
            break
    if iStat == True:
        stats = True
        print(counter)
    counter += 1 

Logic

I found it logical to use a while loop and a counter to solve this problem, because we have a number that has the potential to go on infinitely, and that's why with while we can increase the counter infinitely.

Inside our loop, we have a variable called "iStat", and it gets a False/True value depending on whether the number is divisible or not. When it gets the True value, the loop breaks and the number is printed on the screen.

The most important point here is the numbers we loop through in the for loop. Normally, the question asks for the numbers between 1 - 20, but instead of doing [1,2,3,..,20] we only loop through [11,13,14,16,17,18,19,20], which significantly accelerates our code.

The reason why we can filter out some numbers here is as follows. For the numbers from 1 to 10, the smallest value is already 2520, and since this number is greater than 20, it allows us to eliminate some numbers.

Let's evaluate some of the numbers we have eliminated.

"1" We can remove it as we like because all numbers can be divided by 1.

"2 - Multiples" If the number is greater than 2, it will be divisible by multiples of 2, and since 2520 is greater than 2, we can eliminate 2 and many of its multiples.

"3 - 9" According to the rule of divisibility by 3 to 9, any number divisible by 18 can also be divided by 3 to 9.

To remind those who forget: 1+8 = 9, that is, it is divisible by 9 and 3.

 

To see the correct answer, click here.