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
Python3 time clock()方法
Python print() 函数

Python 输出指定范围内的素数

Document 对象参考手册 Python3 实例

素数(prime number)又称质数,有无限个。除了1和它本身以外不再被其他的除数整除。

以下实例可以输出指定范围内的素数:

实例(Python 3.0+)

#!/usr/bin/python3 # 输出指定范围内的素数 # take input from the user lower = int(input("输入区间最小值: ")) upper = int(input("输入区间最大值: ")) for num in range(lower,upper + 1): # 素数大于 1 if num > 1: for i in range(2,num): if (num % i) == 0: break else: print(num)

执行以上程序,输出结果为:

$ python3 test.py 
输入区间最小值: 1
输入区间最大值: 100
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97

使用试除法

试除法是一种基本的算法,它对每个数进行除法测试以判断是否为素数。以下是使用试除法输出指定范围内素数的代码:

实例

def is_prime(n):
    """判断一个数是否为素数"""
    if n <= 1:
        return False
    if n <= 3:
        return True
    if n % 2 == 0 or n % 3 == 0:
        return False
    i = 5
    while i * i <= n:
        if n % i == 0 or n % (i + 2) == 0:
            return False
        i += 6
    return True

def primes_in_range(start, end):
    """输出指定范围内的素数"""
    for num in range(start, end + 1):
        if is_prime(num):
            print(num)

# 示例:输出 10 到 50 范围内的素数
primes_in_range(10, 50)

使用埃拉托斯特尼筛法

埃拉托斯特尼筛法是一种更高效的算法,尤其适用于找出较大范围内的素数。以下是使用埃拉托斯特尼筛法输出指定范围内素数的代码:

实例

def sieve_of_eratosthenes(max_num):
    """使用埃拉托斯特尼筛法找出 max_num 以内的所有素数"""
    sieve = [True] * (max_num + 1)
    sieve[0] = sieve[1] = False  # 0 和 1 不是素数
    p = 2
    while p * p <= max_num:
        if sieve[p]:
            for multiple in range(p * p, max_num + 1, p):
                sieve[multiple] = False
        p += 1
    return [p for p, is_prime in enumerate(sieve) if is_prime]

def primes_in_range(start, end):
    """输出指定范围内的素数"""
    primes = sieve_of_eratosthenes(end)
    for num in primes:
        if num >= start:
            print(num)

# 示例:输出 10 到 50 范围内的素数
primes_in_range(10, 50)

Document 对象参考手册 Python3 实例

AI 思考中...
Python3 time clock()方法
Python print() 函数

8 篇笔记 写笔记

  1. #0

       hizmz

      hiz***sina.com

    63

    与前面判断是否是质数一样,作者算法中未使用到"开根号法"来节约时间复杂度,同时为加入个数等说明,因此我对其改进如下:

    import math
    
    # 输出指定范围内的素数
    # 用户输入范围
    lower = int(input("输入区间最小值: "))
    upper = int(input("输入区间最大值: "))
    print("素数结果如下:")
    print("="*10)
    pri_num = 0
    com_num = 0
    for num in range(lower, upper + 1):
        # 找到其平方根( √ ),减少算法时间
        square_num = math.floor(num ** 0.5)
        # 素数大于 1
        if num > 1:
            for i in range(2, (square_num + 1)):
                if (num % i) == 0:
                    com_num += 1
                    break
            else:
                pri_num += 1
                print(num)
    print("="*10)
    print(com_num,'个合数')
    print(pri_num,'个素数')
    hizmz

       hizmz

      hiz***sina.com

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

       Pt

      idi***[email protected]

    12

    先定义一个判断素数的函数,然后再输入范围去判断。

    # -*- coding: UTF-8 -*-
    
    # Filename : defprime.py
    # author :Pt
    
    def isprime(x):
        if x == 1:
            return False
        k = int(x**0.5)
        for j in range(2, k + 1):
            if x % j == 0:
                return False
        return True
    lower = int(input("请输入区间最小值:"))
    upper = int(input("请输入区间最大值:"))
    for i in range(lower, upper):
        if isprime(i):
            print(i, end = " ")
    Pt

       Pt

      idi***[email protected]

    9年前 (2017-10-04)
  3. #0

       风林火山

      dra***[email protected]

    12
    prime_number = [x for x in range(int(input('区间最小值:')), int(input('区间最大值:'))) if[] == [y for y in range(2, int(x ** 0.5) + 1) if x % y == 0]]
    
    print(prime_number)
    风林火山

       风林火山

      dra***[email protected]

    9年前 (2017-10-15)
  4. #0

       Transitive

      276***[email protected]

    5

    在已经定于的数值中求所有的素数。

    #在x**y中求素数,千万别作死求太大的数,会没耐心等结果。
    i = 2
    x = input("请输入x的值:")
    y = input("请输入y的值:")
    x = int(x)
    y = int(y)
    s = x**y
    s = int(s)
    while ( i < s ):
        j = 2
        while (j <= (i / j )):
            if not (i % j):
                break
            j = j + 1
        if (j > i / j):
            print(str(i)+",")
        i = i + 1

    这个是求梅森素数的:

    def meisen(n):
        n += 1
        while True:
            k = n % 2
            n = n // 2
            if k != 0:
                return False
            if n == 1:
                break
        return True
    
    def sushu():
        n = 1
        while True:
            if n == 1 or n == 2 or n == 3:
                yield n
            else:
                m = n//2
                flag = False
                for i in range(2,m+1):
                    if n % i == 0:
                        flag = True
                if not flag:
                    yield n
            n += 1
    
    import time
    begin_time = time.time()
    for i in sushu():
        if i > 10000:      #改 i >的值可以增加求取范围
            break
        if meisen(i):
            print(i)
            end_time = time.time()
            print(end_time-begin_time)
            begin_time = end_time
    Transitive

       Transitive

      276***[email protected]

    8年前 (2019-03-08)
  5. #0

       vinson

      wei***[email protected]

    13

    修正重复输出质数的错误:

    lower = int(input("输入区间最小值: "))
    upper = int(input("输入区间最大值: "))
    for num in range(lower,upper + 1):
        if num > 1:
            for i in range(2,num):
                if (num % i) == 0:
                    break
                elif i < (num - 1):
                    continue
                else:
                    print(num)
    vinson

       vinson

      wei***[email protected]

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

       cc河豚

      a12***[email protected]

    8

    把版大的改造了下,增加平方根和只從質數判斷是否為質數,算大數字會快很多。

    import math
    #創建列表儲存質數
    listPM = [2]
    lower = int(input("最小值: "))
    upper = int(input("最大值: "))
    #質數從2開始
    if upper >= 2:
        #平方根減少運算
        for num in range(3,upper + 1):
            S_num = math.sqrt(num)
            #只從質數判斷是否為質數
            for i in listPM:
                if i > S_num:
                    listPM.append(num)
                    break
                if (num % i) == 0:
                    break
        #剔除掉小於的質數
        listPM = [i for i in listPM if i >= lower] 
        print(listPM)
    cc河豚

       cc河豚

      a12***[email protected]

    7年前 (2020-01-02)
  7. #0

       Kindred

      268***[email protected]

    16

    hizmz真大佬,不过代码我研究了很久,还是给大佬加上注释如下,并对负数进行改进,如果需要,还可以自行添加对其他字符串进行限定输入。

    #输出指定范围内的素数
    #非数字字符串会出错,一开始就应该避免错误的发生(限定范围),而不是报错了再来改进,
    #可以继续改进用列表输出质数和合数
    import math
    lower = int(input("输入区间(包括)最小值: "))
    upper = int(input("输入区间(包括)最大值: "))
    sumzs=0
    sumhs=0
    print("素数结果如下:")
    print("="*10)
    
    pri_num = 0
    com_num = 0
    
    for num in range(lower, upper + 1):
        if num > 1:    # 素数大于 1
            square_num = math.floor(num ** 0.5)    # 找到其平方根,减少算法时间
    #++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 
            for i in range(2, (square_num + 1)):  #(2,2)属于空集,不会出错,但也不会执行
                if (num % i) == 0:  #可以被整除说明是合数
                    com_num += 1
                    sumhs+=num
                    print(num,"是合数")
                    break   #执行到这里说明是合数,跳出里层for和所有else语句,执行完其他语句(比如下面注释掉的)后继续外一层for的下一次循环
                else:       #不能被依次整除,说明循环完了还是质数,用pass表示占位
                    pass    #继续执行下一句else语句
    #这里的else和上面的for属于一个级的,能执行下面的语句说明上面的质数筛选已经过关了,没有执行break。           
            else:                  #上面的for模块执行完了,说明都不能被2到平方根的数整除
                pri_num += 1        #所以质数计数+1
                sumzs+=num
                print(num,"是质数")
    #        print(num,"是质数")       #这就是break执行后继续执行的语句,同for和else级别,也就是上面说的其他语句
    #++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 
        else:
            print(num,"既不是素数也不是合数")
    print("="*10)
    print(com_num,'个合数','和为',sumhs)
    print(pri_num,'个素数','和为',sumzs)
    Kindred

       Kindred

      268***[email protected]

    7年前 (2020-02-23)
  8. #0

       不是TheShy是Rookie

      501***[email protected]

    5

    更严谨的判断,更美观的输出:

    import math
    def T1():
        # print("0和1 既不是质数,也不是合数。")
        while True:
            try:
                Max_num = int(input("请输入区间最大值:"))
                Min_num = int(input("请输入区间最小值:"))
            except:
                print("您输入的不是整数。")
            else:
                if (Max_num <= 1 or Min_num <= 1) :
                    print("请重新输入大于“1”的整数。")
                else:
                    if Min_num >= Max_num:
                        print("最大值必须大于最小值,请重新输入。")
                    else:
                        break
        #前面是为了给输入的数字判断,然后传参调用T2()
        T2(Min_num,Max_num)
    
    def T2(A,B):
        L = []                                      #质数空列表
        K = []                                      #合数空列表
        for h in range(A,(B+1)):
            r = math.floor(h**0.5)
            for e in range(2,(r+1)):
                if (h % e) == 0:
                    break
            else:
                L.append(h)                         #得到的质数添加到列表L
        for w in range(A,(B+1)):
            if w not in L:
                K.append(w)                          #将剩下的合数添加到列表K
        print(f"{A} 到 {B} 之间的所有质数如下:\n",L) #以列表形式输出所有质数
        print(f"{A} 到 {B} 之间的所有合数如下:\n",K)
        print("质数共计:",len(L),"个")               #如果要计算个数
        print("合数共计:",len(K),"个")
    
    
    
    if __name__ == "__main__":
        T1()                            #范围内的所有质数(与合数)

    输入 100 和 2 ,结果如下:

    请输入区间最大值:100
    请输入区间最小值:2
    2 到 100 之间的所有质数如下:
     [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
    2 到 100 之间的所有合数如下:
     [4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, 26, 27, 28, 30, 32, 33, 34, 35, 36, 38, 39, 40, 42, 44, 45, 46, 48, 49, 50, 51, 52, 54, 55, 56, 57, 58, 60, 62, 63, 64, 65, 66, 68, 69, 70, 72, 74, 75, 76, 77, 78, 80, 81, 82, 84, 85, 86, 87, 88, 90, 91, 92, 93, 94, 95, 96, 98, 99, 100]
    质数共计: 25 个
    合数共计: 74 个
    不是TheShy是Rookie

       不是TheShy是Rookie

      501***[email protected]

    3年前 (2023-08-30)

点我分享笔记

取消

  • 昵称 (必填)
  • 邮箱 (必填)
  • 引用地址
分类导航
  • 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 01402792 — 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.