GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • 首页
  • HTML
  • JavaScript
  • CSS
  • React
  • Python3
  • Java
  • C
  • C++
  • C#
  • Go
  • SQL
  • Linux
  • VS Code

This view

  • Original page
  • New address

GeezerVison is showing www.runoob.com — Python 质数判断 | 菜鸟教程

菜鸟教程 -- 学的不仅是技术,更是梦想!

  • Vue3 教程
  • Vue2 教程
  • Bootstrap3
  • Bootstrap4
  • Bootstrap5
  • 机器学习
  • PyTorch
  • TensorFlow
  • Sklearn
  • NLP
  • AI Agent
  • Ollama
  • Coding Plan
Python 3 教程
Python3 教程 Python3 简介 Python3 环境搭建 Python3 Pycharm Python3 VScode Python3 基础语法 Python3 基本数据类型 Python3 数据类型转换 Python3 解释器 Python3 注释 Python3 运算符 Python3 数字(Number) Python3 字符串 Python3 列表 Python3 元组 Python3 字典 Python3 集合 Python3 条件控制 Python3 循环语句 Python3 编程第一步 Python3 推导式 Python3 迭代器与生成器 Python3 with Python3 函数 Python3 lambda Python3 装饰器 Python3 数据结构 Python3 模块 Python __name__ Python3 输入和输出 Python3 File Python3 OS Python3 错误和异常 Python3 面向对象 Python3 命名空间/作用域 Python 虚拟环境的创建 Python 类型注解 Python3 标准库概览 Python3 实例 Python 测验

Python3 高级教程

Python3 正则表达式 Python3 CGI编程 Python3 MySQL(mysql-connector) Python3 MySQL(PyMySQL) Python3 网络编程 Python3 SMTP发送邮件 Python3 多线程 Python3 XML 解析 Python3 JSON Python3 日期和时间 Python3 内置函数 Python3 MongoDB Python3 urllib Python uWSGI 安装配置 Python3 pip Python3 operator Python math Python requests Python random Python OpenAI Python 有用的资源 Python AI 绘画 Python statistics Python hashlib Python 量化 Python pyecharts Python selenium 库 Python 爬虫 Python Scrapy 库 Python Markdown Python sys 模块 Python Pickle 模块 Python subprocess 模块 Python queue 模块 Python StringIO 模块 Python logging 模块 Python datetime 模块 Python re 模块 Python csv 模块 Python threading 模块 Python asyncio 模块 Python PyQt
Python 获取最大值函数
Python 阶乘实例

Python 质数判断

Document 对象参考手册 Python3 实例

一个大于1的自然数,除了1和它本身外,不能被其他自然数(质数)整除(2, 3, 5, 7等),换句话说就是该数除了1和它本身以外不再有其他的因数。


test.py 文件:

# -*- coding: UTF-8 -*- # Filename : test.py # author by : www.runoob.com # Python 程序用于检测用户输入的数字是否为质数 # 用户输入数字 num = int(input("请输入一个数字: ")) # 质数大于 1 if num > 1: # 查看因子 for i in range(2,num): if (num % i) == 0: print(num,"不是质数") print(i,"乘于",num//i,"是",num) break else: print(num,"是质数") # 如果输入的数字小于或等于 1,不是质数 else: print(num,"不是质数")

执行以上代码输出结果为:

$ python3 test.py 
请输入一个数字: 1
1 不是质数
$ python3 test.py 
请输入一个数字: 4
4 不是质数
2 乘于 2 是 4
$ python3 test.py 
请输入一个数字: 5
5 是质数

Document 对象参考手册 Python3 实例

AI 思考中...
Python 获取最大值函数
Python 阶乘实例

11 篇笔记 写笔记

  1. #0

       hizmz

      hiz***sina.com

    127

    原作者的算法基本正确,但时间复杂度较高,在判断一个大数是质数还是合数的情况下,应该在查看因子那里的循环中使用到平方根。代码如下:

    # Python 程序用于检测用户输入的数字是质数还是合数
    import math
    # 用户输入数字
    num = int(input("请输入一个数字: "))
    # 质数大于 1
    if num > 1:
        # 找到其平方根( √ ),减少算法时间
        square_num = math.floor( num ** 0.5 )
        # 查找其因子
        for i in range(2, (square_num+1)): #将平凡根加1是为了能取到平方根那个值
            if (num % i) == 0:
                print(num, "是合数")
                print(i, "乘于", num // i, "是", num)
                break
        else:
            print(num, "是质数")
            # 如果输入的数字小于或等于 1,不是质数
    else:
        print(num, "既不是质数,也不是合数")

    原理是用了开根号法:

    假如一个数N是合数,它有一个约数a,那么有a×b=N

    则a、b两个数中必有一个大于或等于根号N,一个小于或等于根号N。

    因此,只要小于或等于根号N的数(1除外)不能整除N,则N一定是素数。

    hizmz

       hizmz

      hiz***sina.com

    9年前 (2017-09-14)
  2. #0

       cindyliu

      916***[email protected]

    15
    # -*- coding: UTF-8 -*-
      
    #用while循环,进行质数判断
    #输入数字
    
    num = int(input("输入一个数字:"))
    #定义i
    i = 2
    while i < num:
        s = num % i
        if s == 0:
            print("{}能被除的数其中有{}".format(num,i))
            break
        else:
            i += 1
    if num == i:
        print("是质数")
    else:
        print("不是质数")
    cindyliu

       cindyliu

      916***[email protected]

    9年前 (2017-12-07)
  3. #0

       TwoIceBing

      139***[email protected]

    18

    输出1-100以内的质数:

    count = 0
    for i in range(1, 101):
        for j in range(1, i):
            if j == i // 2 and i % j == 1 or (i <= 3 and i != 1):
                if count == 4:
                    print(i)
                    count = 0
                else:
                    print(i, end='\t')
                    count += 1
                break
            if i % j == 0 and j != 1:
                break
    TwoIceBing

       TwoIceBing

      139***[email protected]

    9年前 (2017-12-07)
  4. #0

       zacharyvic

      194***[email protected]

    6

    用质数表来判断是否为质数

    # -*- coding: UTF-8 -*-
    # Python 程序用于检测用户输入的数字是否为质数
    # 用户输入数字
    num = int(input("请输入一个数字: "))
    # 获取小于等于num平方根的质数表
    def getPrimeList(n, oldPrimeList):
        for prime in oldPrimeList:
            if (n % prime) == 0:
                break
        if prime == oldPrimeList[-1]:
            oldPrimeList.append(n)
    # 2,3是质数
    if num == 2 or num == 3:
        print(num, "是质数")
    # 对大于3的数用质数表来判断
    elif num > 3:
        judge_num = int(num ** 0.5) + 1
        primeList = [2]
        for i in range(2, judge_num):
            getPrimeList(i, primeList)
        for i in primeList:
            if (num % i) == 0:
                print(num, "不是质数")
                break
        else:
            print(num, "是质数")
    # 如果输入的数字小于或等于 1,不是质数
    else:
        print(num, "不是质数")
    zacharyvic

       zacharyvic

      194***[email protected]

    9年前 (2018-04-27)
  5. #0

       freejustin

      fre***[email protected]

    6

    参考方法:

    # 用户输入数字
    num = int(input("请输入一个数字: "))
    # 质数大于 1
    if num > 1:
       # 查看因子
       for i in range(2, (int(num/2)+1) ):
           if (num % i) == 0:
               print(num,"不是质数")
               print(i,"乘于",num//i,"是",num)
               break
       else:
           print(num,"是质数")
    # 如果输入的数字小于或等于 1,不是质数
    else:
       print(num,"不是质数")
    freejustin

       freejustin

      fre***[email protected]

    9年前 (2018-06-09)
  6. #0

       freejustin

      fre***[email protected]

    9

    参考方法:

    from math import sqrt
    
    def is_prime(n):
        if n == 1:
            return False
        for i in range(2, int(sqrt(n))+1):
            if n % i == 0:
                return False
        return True
    
    # 用户输入数字
    num = int(input("请输入一个数字: "))
    if is_prime(num):
        print(num,"是质数")
    else:
        print(num,"不是质数")
    freejustin

       freejustin

      fre***[email protected]

    9年前 (2018-06-09)
  7. #0

       vinson

      wei***[email protected]

    4

    加入整数判断:

    while True:
        try:
            num=int(input('输入一个整数:')) #判断输入是否为整数
        except ValueError: #不是纯数字需要重新输入
            print("输入的不是整数!")
            continue
        break
    if num <= 1:
        print(num,"小于1的不是质数")
    else:
        for i in range(2,num):
            if (num % i) == 0:
                print(num,"不是质数")
                print(i,"乘于",num//i,"是",num)
                break
            elif i < (num-1):
                continue
            else:
                print(num,"是质数")
    vinson

       vinson

      wei***[email protected]

    8年前 (2019-03-20)
  8. #0

       小土豆

      176***[email protected]

    15

    Python3 计算质数 (厄拉多塞筛法)

    # ls3[1:6:2] -- 起始位置为 2,终止位置为 6,步长为2 
    def countPrimes(self, n: int) -> int:
            if n < 3:
                return 0     
            else:
                # 首先生成了一个全部为1的列表
                output = [1] * n
                # 因为0和1不是质数,所以列表的前两个位置赋值为0
                output[0],output[1] = 0,0
                 # 此时从index = 2开始遍历,output[2]==1,即表明第一个质数为2,然后将2的倍数对应的索引
                 # 全部赋值为0. 此时output[3] == 1,即表明下一个质数为3,同样划去3的倍数.以此类推.
                for i in range(2,int(n**0.5)+1): 
                    if output[i] == 1:
                        output[i*i:n:i] = [0] * len(output[i*i:n:i])
             # 最后output中的数字1表明该位置上的索引数为质数,然后求和即可.
            return sum(output)
    小土豆

       小土豆

      176***[email protected]

    7年前 (2019-09-23)
  9. #0

       小无然

      ysl***[email protected]

    3

    参考:

    while 1:
        try:
            a = int(input('请输入一个需要判断是否是质数的数:'))
            if a <= 0:
                print('请输入一个正整数。')
            elif a == 1:
                print('1不是质数也不是合数。')
            elif a == 2:
                print('2是质数。')
            else:
                for i in range(2, a):
                    if a % i == 0:
                        print('{0}是合数,{0}={1}×{2}。'.format(a, i, a//i))
                        break
                else:
                    print('{0}是质数。'.format(a))
        except ValueError:
            print('请输入一个数。')
    
    小无然

       小无然

      ysl***[email protected]

    7年前 (2019-11-01)
  10. #0

       学海无牙

      yj.***[email protected]

    4

    参考:

    lower_range = int(input('Key in the lower range: '))
    upper_range = int(input('Key in the upper range: '))
    
    list_prime = []
    num_prime = 0
    
    # 定义一个函数来判断给定一个数n是否是质数,输入True(质数),False(合数)
    def is_prime(n):
        
        decision = False
        
        for i in range(2, n):
            if n % i == 0:
                decision = False
                return decision
                break
            else:
                continue
        
        decision = True
        return decision
    
    for i in range(lower_range, upper_range+1):
    
        outcome = is_prime(i)
    
        if outcome == True:
            list_prime.append(i)
            num_prime += 1
        else:
            continue
    
    print(list_prime)
    print(num_prime)
    学海无牙

       学海无牙

      yj.***[email protected]

    7年前 (2019-12-23)
  11. #0

       Kindred

      268***[email protected]

    7

    企图结合平方根算法和厄拉多塞筛法一起用,但是代码会复杂很多,转念一想,如果遍历剔除倍数的操作 比 一个个判断整除的操作 ,并没有省去多长时间,那么可能就不如直接用平方根算法了吧。

    赞同 hizmz 的代码原理,补充一下注释吧,大佬牛逼。

    # 用平方根算法减少时间
    import math
    # 用户输入数字
    num = int(input("请输入一个数字: "))
    # 质数大于 1
    if num > 1:
        #因为向上向下取整的函数对于整数来说都是自身,所以要想查找因子必须+1来包括自身
        #所以用的是向下取整函数,否则向上取整后比如平方根是5.2>>6>>7多算一个6
        pingfanggeng = math.floor( num ** 0.5 )
        # 查找其因子
        for i in range(2, pingfanggeng+1): #向下取整后需要加一来判断平方根位的因数,包括平方根
            if (num % i) == 0:
                print(num, "是合数")
                print(i, "乘于", num // i, "是", num)
                break
        else:
            print(num, "是质数")
            # 如果输入的数字小于或等于 1,那就不是质数
    else:
        print(num, "既不是质数,也不是合数")
    Kindred

       Kindred

      268***[email protected]

    7年前 (2020-02-23)

点我分享笔记

取消

  • 昵称 (必填)
  • 邮箱 (必填)
  • 引用地址
分类导航
  • Python / 数据科学
    • Python 教程
    • Python2.x 教程
    • FastAPI 教程
    • Flask 教程
    • Django 教程
    • NumPy 教程
    • Pandas 教程
    • SciPy 教程
    • Matplotlib 教程
    • Dash 教程
    • Jupyter Notebook 教程
    • Pillow 教程
    • 量化交易
    • R 教程
    • Julia 教程
  • AI / 智能开发
    • AI Agent(智能体)
    • AI(人工智能)
    • AI 应用案例
    • Codex 教程
    • Vibe Coding 教程
    • Claude Code
    • OpenCode
    • Skills(技能)
    • Ollama 教程
    • Hermes Agent
    • DeepSeek Harness
    • Pi Agent
    • AI 数学基础
    • TensorFlow 教程
    • PyTorch 教程
    • Scikit-learn 教程
    • 机器 教程
    • LangChain
    • 自然语言处理 NLP
    • OpenCV 教程
    • Selenium 教程
    • Playwright 教程
  • 前端开发
    • HTML 教程
    • HTML5 教程
    • CSS 教程
    • CSS3 教程
    • JavaScript 教程
    • HTML DOM 教程
    • TypeScript 教程
    • AJAX 教程
    • JSON 教程
    • Tailwind CSS 教程
    • Bootstrap4 教程
    • Bootstrap5 教程
    • Foundation 教程
    • Vue.js 教程
    • Vue3 教程
    • React 教程
    • Next.js 教程
    • Three.js 教程
    • AngularJS 教程
    • Angular 教程
    • jQuery 教程
    • jQuery UI 教程
    • jQuery EasyUI 教程
    • ECharts 教程
    • Chart.js 教程
    • Highcharts 教程
    • Google 地图 教程
    • SVG 教程
    • Font Awesome 教程
  • 后端开发
    • Node.js 教程
    • Electron 教程
    • PHP 教程
    • Java 教程
    • Go 教程
    • Rust 教程
    • C# 教程
    • Unity 教程
    • Servlet 教程
    • JSP 教程
    • ASP 教程
    • AppML 教程
    • VBScript 教程
    • Swagger 教程
    • RESTful API 教程
    • Docker 教程
    • Linux 教程
    • ZooKeeper 教程
  • 数据库
    • SQL 教程
    • MySQL 教程
    • PostgreSQL 教程
    • SQLite 教程
    • MongoDB 教程
    • Redis 教程
    • Memcached 教程
  • 移动开发
    • Android 教程
    • Flutter 教程
    • Ionic 教程
    • jQuery Mobile 教程
    • Swift 教程
    • Kotlin 教程
  • DevOps / 工程化
    • Git 教程
    • SVN 教程
    • CMake 教程
    • Maven 教程
    • VS Code 教程
    • Obsidian 教程
    • PyCharm 教程
    • Eclipse 教程
    • Markdown 教程
    • LaTeX 教程
  • 编程语言
    • C 教程
    • C++ 教程
    • Zig 教程
    • Scala 教程
    • Ruby 教程
    • Perl 教程
    • Lua 教程
    • Dart 教程
    • 汇编语言 教程
    • Verilog 教程
  • 计算机基础
    • 计算机组成原理
    • 数据结构与算法
    • C 语言数据结构与算法
    • 设计模式
    • Python 设计模式
    • 正则表达式
    • HTTP 教程
    • TCP/IP 教程
    • 网络协议
    • W3C 教程
  • XML / Web Service
    • XML 教程
    • DTD 教程
    • XML DOM 教程
    • XSLT 教程
    • XPath 教程
    • XQuery 教程
    • XLink 教程
    • XPointer 教程
    • XML Schema 教程
    • XSL-FO 教程
    • Web Service 教程
    • WSDL 教程
    • SOAP 教程
    • RSS 教程
    • RDF 教程
  • .NET
    • ASP.NET 教程
    • MVC 教程
    • Razor 教程
    • Web Forms 教程
    • Web Pages 教程
    • PowerShell 教程
  • 网站建设
    • 网站建设指南
    • 浏览器信息
    • 网站主机教程
    • 网站品质

字节 Coding Plan 限时 9.9 元起,支持 Deepseek-V4、GLM-5.3、Doubao-Seed-Evolving、Kimi-K3。
百度 Dumate 百度推出的桌面级 AI 智能体。 输入激活码送 4000 积分
使用文档
Trae AI 原生开发环境,让编程更高效。新用户注册赠2500积分,管理项目,也交付成果。
Advertisement
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.