Home >Backend Development >Python Tutorial >Python programming to determine whether a positive integer is a prime number sample code sharing

Python programming to determine whether a positive integer is a prime number sample code sharing

黄舟
黄舟Original
2017-04-15 09:31:174483browse

This article mainly introduces PythonProgrammingHow to determine whether a positive integer is a prime number, involving operating skills related to Python mathematical operations, friends in need You can refer to the following

The example of this article describes the method of Python programming to determine whether a positive integer is a prime number. Share it with everyone for your reference, the details are as follows:

import string
import math
#判断是否素数的函数
def isPrime(n):
  if(n<2):
    return False;
  elif(n==2):
    return True;
  elif(n>2):
    for d in range(2,int(math.ceil(math.sqrt(n))+1)):
      if(n%d==0):
        return False;
  return True;
num=input();
strNum=list(str(num)) #将输入值转换为List字符串
flag=True; #设置一个标志位
#以下循环用于对用户输入数值进行循环位移后得到的所有结果
for i in range(0,len(strNum)):
  lastP=strNum.pop();#获取并删除最后一位
  strNum.insert(0,lastP);#将上一步删除的数字添加到最前面
  stempNumStr=&#39;&#39;; #用于保存某一步位移结果的临时变量
  for each in strNum:
    stempNumStr+=each;#将位移后的字符串合并
  stempNum=string.atoi(stempNumStr);#转换为整形
#或者 stempNum= ( num//(10**i) ) + (num%(10**i))*(10**(lens-i))
  if(isPrime(stempNum)==False):#再判断位移后的这个数是否是素数,如果不是
    flag=False;#则直接判定当前用户输入的数字不是循环素数
    print(&#39;%s not Loop prime number&#39;%num);
    break;#并中止后续计算,退出循环
if(flag==True):#如果Flag的值依然为True,说明这个数一定是循环素数
  print(&#39;%s is Loop prime number&#39;%num);

The running results are as follows:

The above is the detailed content of Python programming to determine whether a positive integer is a prime number sample code sharing. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn