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)
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.
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.
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)
.
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.
To avoid traps like this one, consider using
if ...
elif ...
elif ...
else ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With