python二级练习(8)

栏目: Python · 发布时间: 8年前

内容简介:python二级练习(8)

8. 输入一个数,判断这个数是否为素数,并输出判断结果。

(所谓素数,是指除了1和该数本身之外,不能被其它任何整数整除的大于1的数。)

解法一:

#python 3.6
#蔡军生 
#http://blog.csdn.net/caimouse/article/details/51749579
#
import random

isPrime = False
num = int(input('请输入一个整数:'))
for i in range(2, num):
    if num % i == 0:
        isPrime = True
        break;
    
if isPrime or num == 1:
    print(num, ' 不是一个素数')
else:
    print(num, ' 是一个素数')

输出如下:

请输入一个整数:100

100  不是一个素数

解法二:

#python 3.6
#蔡军生 
#http://blog.csdn.net/caimouse/article/details/51749579
#
from math import sqrt


isPrime = True
num = int(input('请输入一个整数:'))


if num == 2 or num == 3:
    isPrime = True
elif num == 1 or num % 6 != 1 and num % 6 != 5:
    isPrime = False
else:
    for i in range(5, int(sqrt(num)) + 1, 6):
        print(i)
        if num % i == 0 or num % (i + 2) == 0:
            isPrime = False
#    
if isPrime:
    print(num, ' 是一个素数')
else:
    print(num, ' 不是一个素数')

最后一种解决法是快速的判断方法。

首先看一个关于质数分布的规律:大于等于5的质数一定和6的倍数相邻。例如5和7,11和13,17和19等等;

证明:令x≥1,将大于等于5的自然数表示如下:

······ 6x-1,6x,6x+1,6x+2,6x+3,6x+4,6x+5,6(x+1),6(x+1)+1 ······

可以看到,不在6的倍数两侧,即6x两侧的数为6x+2,6x+3,6x+4,由于2(3x+1),3(2x+1),2(3x+2),所以它们一定不是素数,再除去6x本身,显然,素数要出现只可能出现在6x的相邻两侧。这里有个题外话,关于孪生素数,有兴趣的道友可以再另行了解一下,由于与我们主题无关,暂且跳过。这里要注意的一点是,在6的倍数相邻两侧并不是一定就是质数。

比特币源码入门教程

https://edu.csdn.net/course/detail/6998

深入浅出Matplotlib

https://edu.csdn.net/course/detail/6859

深入浅出Numpy

http://edu.csdn.net/course/detail/6149

Python游戏开发入门

http://edu.csdn.net/course/detail/5690

你也能动手修改C编译器

http://edu.csdn.net/course/detail/5582


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Beginning Google Maps API 3

Beginning Google Maps API 3

Gabriel Svennerberg / Apress / 2010-07-27 / $39.99

This book is about the next generation of the Google Maps API. It will provide the reader with the skills and knowledge necessary to incorporate Google Maps v3 on web pages in both desktop and mobile ......一起来看看 《Beginning Google Maps API 3》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

URL 编码/解码
URL 编码/解码

URL 编码/解码

MD5 加密
MD5 加密

MD5 加密工具