用python写的一个判断是否为质数的函数

 

#!/usr/bin/python
# Judge whether a interger is a prime.
#isprime.py

import sys
import math

def isPrime(num):
    if not isinstance(num, int):
       return False
    anum = num
    if anum < 0:
       anum = math.fabs(anum)
    if anum == 1:
       return False
    if anum == 2 or anum == 3:
       return True
    if math.fmod(anum, 2) == 0:
       return False
    endN = math.sqrt(anum) + 1
    i = 3
    ret = True
    while i < endN:
       if math.fmod(anum, i) == 0:
          ret = False
          break;
       i += 2
    return ret

if __name__ == "__main__":
      if len(sys.argv) < 2:
         print "usage is:"
         print "python isprime.py <value1> [< <space>value2>< <space>value3>...]"
      numlist = sys.argv[1:]
      n = 0
      for num in numlist:
          try:
             n = int(num)
             if isPrime(n) :
                print num + " is a prime."
             else :
                print num + " is not a prime."
          except ValueError:
                print num + " is not a prime."

作者:豆博草堂

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

请拖动滑块 *