Project Euler 5 in Python - How can I optimize my solution?

后端 未结 20 1114
醉梦人生
醉梦人生 2020-11-30 08:00

I\'ve recently been working on Project Euler problems in Python. I am fairly new to Python, and still somewhat new as a programmer.

In any case, I\'ve ran into a sp

20条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 08:33

    I wrote a solution to euler5 that:

    • Is orders of magnitude faster than most of the solutions here when n=20 (though not all respondents report their time) because it uses no imports (other than to measure time for this answer) and only basic data structures in python.
    • Scales much better than most other solutions. It will give the answer for n=20 in 6e-05 seconds, or for n=100 in 1 millisec, faster than most of the responses for n=20 listed here.

      import time
      a=time.clock() # set timer
      
      j=1
      factorlist=[]
      mydict={}
      # change second number to desired number +1 if the question were changed.
      for i in range(2,21,1):
          numberfactors=[]
          num=i
          j=2
      # build a list of the prime factors
          for j in range(j,num+1,1):
              counter=0
              if i%j==0:
                  while i%j==0:
                      counter+=1
                      numberfactors.append(j)
                      i=i/j
      # add a list of factors to a dictionary, with each prime factor as a key
                      if j not in mydict:
                          mydict[j] = counter
      # now, if a factor is already present n times, including n times the factor
      # won't increase the LCM. So replace the dictionary key with the max number of
      # unique factors if and only if the number of times it appears is greater than
      # the number of times it has already appeared.
      # for example, the prime factors of 8 are 2,2, and 2. This would be replaced 
      # in the dictionary once 16 were found (prime factors 2,2,2, and 2).
                  elif mydict[j] < counter:
                      mydict[j]=counter
      
      total=1
      for key, value in mydict.iteritems():
          key=int(key)
          value=int(value)
          total=total*(key**value)
      
      b=time.clock()
      elapsed_time=b-a
      print total, "calculated in", elapsed_time, "seconds"
      

      returns:

      232792560 calculated in 6e-05 seconds
      
      # does not rely on heuristics unknown to all users, for instance the idea that 
      # we only need to include numbers above 10, etc.
      
      
      # For all numbers evenly divisible by 1 through 100:
      69720375229712477164533808935312303556800 calculated in 0.001335 seconds
      

提交回复
热议问题