关于小悟志网站地图归档友情链接联系Feed

云上小悟 + 

首页 » InfoTech »

找出所有素数(Python版)

InfoTech
2016年11月14日 / 28次阅读
标签:麦新杰用Python

文章《找出所有素数(Python版)》的特色图片

在一个范围内,将这个范围内的所有素数找出来。

我用Python写了一个函数来实现这个功能,具体如下:

还在学习Python过程中,所有注释比较多。

 

def PrimeNumber(EndNum=100, StartNum=2): 
    # you can only leave the StartNum be default or both while calling
    """ Display prime number sequence
    Positive integer argument ONLY.
    Please do not make the difference between StartNum and EndNum too big.
    PrimeNumber() means default argument value from 2 to 100.
    PrimeNumber(500) means display all prime number from 2 to 500.
    PrimeNumber(500, 300) means display all prime number from 300 to 500.
    """
    #input type and validation check
    if type(StartNum) is not int:
        return
    if type(EndNum) is not int:
        return
    if (StartNum < 0) or (EndNum < 0):
        return
    
    if StartNum < 2:
        StartNum = 2 # start point
    if StartNum > EndNum:
        return
    
    total = 0
    print('Calculating...hope the number is not very big...')
    for i in range(StartNum, EndNum+1):
        for j in range(2, int(i/2)+1): #if int(i/2)+1<=2, it'll run into else clause directly; use int(i/2)+1 to make it faster.
            if i%j == 0: # find a divisor
                break; # not a prime number and else will not be executed
        else: # after for loop is over except break
            # total++ is not supported in Python
            #total = total + 1
            total += 1
            print('  ',i)
    
    print('Total:', total)
    return
#---- End of Function: PrimeNumber

 

本文链接:http://www.maixj.net/ict/sushu-python-13598
云上小悟 麦新杰(QQ:1093023102)

相关文章

评论是美德

无力满足评论实名制,评论对非实名注册用户关闭,有事QQ:1093023102.


前一篇:
后一篇:

栏目精选


©Copyright 麦新杰 Since 2014 云上小悟独立博客版权所有 备案号:苏ICP备14045477号-1

网站二维码
拍拍贷
go to top