How to determine whether python inputs a number n to determine whether it is a prime number

coldplay.xixi
Release: 2023-01-03 09:28:05
Original
61884 people have browsed it

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.

How to determine whether python inputs a number n to determine whether it is a prime number

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, "是合数!")
Copy after login

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, "是合数!")
Copy after login

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(&#39;%d&#39; % m,end=&#39; &#39;)
    n += 1
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template