New to programming, compute time seems very long for this Python code -


so new programmer, studying cs in university. new python , have been solving project euler puzzles, , wondering why number 5 takes long compute! looks 287 seconds. correct answer, compute time long. can explain me why is, , how better optimize run faster?

for unfamiliar project euler, question asking me find first positive number divisible numbers 1 through 20.

edit: guys. don't know how comment on comments suggestions have been helpful. thanks!!

import time def main():     time_start = time.clock()     x=2     while true:         if divby20(x)==true:             print(x)             break         else:             x=x+1      time_elapsed = (time.clock() - time_start)     print(time_elapsed)  def divby20(a):     in range(1,21):         if a%i!=0:             return false     return true  main() 

your program loops on every possible number one-by-one until finds solution. brute force solution. project euler questions designed foil brute force approaches. requires cleverness improve upon direct approach. means refining answer. means rethinking it.

refine

this problem great example. make incremental improvements algorithm. instance, know answer must even, why not skip odd numbers?

x = x + 2 

in fact, must divisible 3, count in multiples of 6.

x = x + 6 

and must divisible 5, right? heck, let's count 30 @ time. we're cooking!

x = x + 30 

you keep following line of thinking , make increment bigger , bigger. time step back. let's rethink whole approach. need iterate @ all? where's headed?

rethink

if multiplied 1×2×3×4×5...×19×20, we'd have a number divisible 1 through twenty. wouldn't smallest such number.

why that? well, reason it's big because of overlap between numbers. don't have multiply 2 if we're going multiply 4. don't have multiply 3 if we're going multiply 6.

the breakthrough multiply prime factors. don't need 6 because we'll have 2 , 3. don't need 9 if multiply 2 3's.

the question is, how many of each prime factor need? how many 2's? how many 3's? answer: need enough cover numbers 20. we'll need 4 2's because 16 = 24. don't need five, because no number has 5 2's in it. we'll need 2 3's handle 9 , 18. , we'll need 1 each of 5, 7, 11, 13, 17, , 19—no number has more once.

and that, can calculate answer hand. don't need program!

24 × 32 × 5 × 7 × 11 × 13 × 17 × 19 = 232,792,560


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -