Home > Article > Backend Development > How to determine whether python inputs a number n to determine whether it is a prime number
How to input a number n in python to determine whether it is a prime number: 1. Use for loop and break statement, the code is [for i in range(2, k 2):if m % i == 0:break ]; 2. Use while loop and bool variables.
The operating environment of this tutorial: Windows 7 system, python version 3.9, DELL G3 computer.
How to input a number n in python to determine whether it is a prime number:
Prime number (also called prime number) means that it cannot be changed by any positive number except 1 and the number itself. A positive integer that is divisible by an integer. To determine whether a positive integer m is a prime number, you only need to determine whether m can be divisible by any positive integer from 2 to the root m. If m cannot be divided by any positive integer in this range, m is a prime number. Otherwise, m is a composite number. number.
Method one: (Using for loop and break statement)
import math m = int(input("请输入一个整数(>1):")) k = int(math.sqrt(m)) for i in range(2, k+2): if m % i == 0: break #可以整除,肯定不是素数,结束循环 if i == k+1: print(m, "是素数!") else: print(m, "是合数!")
Method two: (Using while loop and bool variable)
import math m = int(input("请输入一个整数(>1):")) k = int(math.sqrt(m)) flag = True #假设输入的整数为素数 i = 2 while (i <= k and flag == True): if (m % i == 0): flag = False #可以整除,肯定不是素数,结束循环 else: i += 1 if (flag == True): print(m, "是素数!") else: print(m, "是合数!")
Example: Print all prime numbers between 100 and 200, output 10 per line
import math;n=0 for m in range(101,201,2): k = int(math.sqrt(m)) for i in range(2,k+2): if m % i == 0:break if i == k+1: if n % 10 == 0:print() print('%d' % m,end=' ') n += 1
Related free learning recommendations: python video tutorial
The above is the detailed content of How to determine whether python inputs a number n to determine whether it is a prime number. For more information, please follow other related articles on the PHP Chinese website!