质数(Python 3)

Prime number(Python 3)

我的目标是构建一个程序,说明是不是素数。 如果 2 和 sqrt(n) 之间没有数字,则正整数 n > 2 是质数 除以 n.

这是我的代码:

import math

def main():
     print("Prime number or not")
     try:
          N = -1
          while N<2:
              print("Error!Enter numbers greater than two")
              N = int(input("Enter the right number:"))
              values = list(range(2,round(math.sqrt(N))))
              for i in values:
                  if i%N !=0:
                      continue
                  x = print("The number is not prime")
                 elif i%N ==0:
                     break
                 x = print("The number is NOT prime")
           print(x)

    except ValueError:
        print("Error!Print correct number")
    except NameError:
        print("Error!Print the numbers")

main()

但是在行中显示语法错误

elif i%N ==0:

请给我一些建议,告诉我如何更正此错误以及一般代码。我是新手Python,所以任何帮助和批评都会很好! 谢谢

假设问题的缩进现在是正确的,问题是您的 elif 块没有 if 父块。它的缩进也是错误的,即使你修复了第一个错误也会抛出一个 IndentationError 但这几乎离题了。

for i in values:
    if i%N !=0:
        continue
    x = print("The number is not prime")  # huh? you've left the `if` block
   elif i%N ==0:  # under-indented
       break

如果您希望这成为您的整个计划,这是我的解决方案:

# Get num
num = input('Input a whole number: ')

# Is num valid
try:
  num = int(num)
  if num < 1 or num > 1000000000000:
    print('Your field cannot be greater than one quantillion or less than one.')
  else:
    # Is num 2 or 5, if yes, prime.
    if num != 2 and num != 5:
      # Is the last number of num 0, 2, 4, 5, 6, or 8, if yes, composite.
      lastNum = str(num)[-1]
      if lastNum == '0' or lastNum == '2' or lastNum == '4' or lastNum == '5' or lastNum == '6' or lastNum == '8':
        print('Your number is composite.')
        if lastNum == '5':
          print(str(num) + ' is divisible by 5.')
        else:
          print(str(num) + ' is divisible by 2.')
      else:
        # List multiples of 3 less than 123, call it multiplesOf3.
        multiplesOf3 = []
        appendMultiple = 0
        for i in range(40):
          appendMultiple += 3
          multiplesOf3.append(appendMultiple)
        # Get sum of all numbers in num, name is sumOfNum
        sumOfNum = 0
        numStr = str(num)
        for i in range(len(numStr)):
          sumOfNum += int(numStr[i])
        # Is sumOfNum in multiplesOf3? 
        numMultipleOf3 = sumOfNum in multiplesOf3
        if numMultipleOf3 == True:
          print('Your number is composite.\n' + str(num) + ' is divisible by 3.')
        else:
          print('Your number is prime.')
    else:
      print('Your number is prime') 
except:
  print('Your field needs to be a whole number. Make sure there is no decimal points (i.e. 12.0 will not be accepted).')

但是如果你希望它只是一个函数,这是我的解决方案(确保你输入一个参数,它需要 1 个参数;输入你的数字。)

 def isPrime(num): 
  try:
    num = int(num)
    if num < 1 or num > 1000000000000:
      print('Your field cannot be greater than one quantillion or less than one.')
    else:
      # Is num 2 or 5, if yes, prime.
      if num != 2 and num != 5:
        # Is the last number of num 0, 2, 4, 5, 6, or 8, if yes, composite.
        lastNum = str(num)[-1]
        if lastNum == '0' or lastNum == '2' or lastNum == '4' or lastNum == '5' or lastNum == '6' or lastNum == '8':
          print('Your number is composite.')
          if lastNum == '5':
            print(str(num) + ' is divisible by 5.')
          else:
            print(str(num) + ' is divisible by 2.')
        else:
          # List multiples of 3 less than 123, call it multiplesOf3.
          multiplesOf3 = []
          appendMultiple = 0
          for i in range(40):
            appendMultiple += 3
            multiplesOf3.append(appendMultiple)
          # Get sum of all numbers in num, name is sumOfNum
          sumOfNum = 0
          numStr = str(num)
          for i in range(len(numStr)):
            sumOfNum += int(numStr[i])
          # Is sumOfNum in multiplesOf3? 
          numMultipleOf3 = sumOfNum in multiplesOf3
          if numMultipleOf3 == True:
            print('Your number is composite.\n' + str(num) + ' is divisible by 3.')
          else:
            print('Your number is prime.')
      else:
        print('Your number is prime') 
  except:
    print('Your field needs to be a whole number. Make sure there is no decimal points (i.e. 12.0 will not be accepted).')

另一种方式,

def isprime(n):
  if min(n//2,n//3,n//5) == 1:
    return True
  elif min(n%2,n%3,n%5) == 0:
    return False
  return True

这个短多了!