Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function running way too slow

Tags:

python

I am practicing Python with Project Euler, question 1, but the function I wrote to solve it is taking way too long.

I figure it's because the way I coded it not the actual method itself.
When I run this function with 10 or 15 iterations it spits out an answer instantly, but as soon as I jump it up to even 20, it doesn't show me anything for even minutes.
This is obviously a big problem if I need to go to 1000 iterations.

def pe1(n):
    counter = 1
    total = 0
    while counter < n:
        if counter%3==0:
            total=total+counter
        if counter%5==0:
            if counter%3==0:
                continue
            total=total+counter
        if counter % 25 == 0:
            print (total)
        counter=counter+1
    return (total)
like image 641
user2709431 Avatar asked Aug 23 '13 02:08

user2709431


People also ask

Why is my computer running so slow all of a sudden?

PCs can slow down when the storage drive is full to the brim. Your PC needs a certain amount of available space in the storage drive. It allows the CPU to swap files and store temporary files. Lack of memory makes these tasks difficult or impossible.

What is slowing down my computer?

Here are some of the things that may have caused your computer to become so slow: Running out of RAM (Random Access Memory) Running out of disk drive space (HDD or SSD) Old or fragmented hard drive. Too many background programs.


3 Answers

Because as soon as counter hits 15, your loop goes into an infinite continue - it's always going to hit the second if statement's case.

You need to move your counter = counter + 1 line before the continue, or better yet, use something like for counter in range(1,n).

like image 142
Amber Avatar answered Oct 13 '22 21:10

Amber


Consider the case if counter equals 15 and look at what happens where counter%5==0 and counter%3==0, which will first occur at that time.

Consider also what will not happen for that value of counter, specifically, the line counter=counter+1 won't be executed.

like image 33
Simon Avatar answered Oct 13 '22 19:10

Simon


To avoid traps like this one, consider using

if ...
elif ...
elif ...
else ...
like image 30
bzdjamboo Avatar answered Oct 13 '22 21:10

bzdjamboo