Python社区  »  Python

最近想重构一个函数,遇到个奇怪的问题,程序无故变慢

爱乐平 • 1 月前 • 68 次点击  

最近想重构一个质数函数,遇到个奇怪的问题,在 is_Prime里面如果我把

if i > Number//3:

  return True

换成函数speedUp_Prime速度就会慢很多,从9秒变成14秒,我根本没做什么修改,请问有没有人遇到类似情况?到底是什么问题? 加个函数就变慢么?那我又加了个is_even的函数和speedUp_Prime差不多,速度也没变啊。

# -*- coding: UTF-8 -*-

def get_Prime_Fast(MinNum,MaxNum):#get all Prime in Range(MinNum,MaxNum),print out
    n=1    
    for i in range(MinNum,MaxNum):
       if is_Prime(i):
           print(n,i)
           n += 1

def is_Prime(Number):#Number is a Prime or not,return boolean
    if Number==2 or Number ==5:# 2 and 5 are Prime
        return True 
    if is_even(Number) or Number%10 ==5 :#Prime Not Even and last Number Not 5
        return False 

    i=0
    for i in range(3,Number,2):#already remove even,so start at 3 step 2
        if(Number%i == 0):
            return False
#          if speedUp_Prime(i,Number):
#              return True
        if i > Number//3:#speedUp_Prime is slower then this,they are same but why this is faster?
                return True   
    else:#After calculate all Number
        return True


def speedUp_Prime(i,Number):#Shall we have to divide all number?
      if i > Number//3:
            return True

def is_even(Number):#Number is Even or not,return boolean
    if Number % 2 ==0:
        return True
    else:
        return False

if __name__=='__main__':
    import time
    start = time.time()
    get_Prime_Fast(2,100000)
    end = time.time()
    print (end-start)
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/53011
 
68 次点击  
分享到微博