python求素数算法_Python程序最多可计算n个质数(使用不同算法)

python求素数算法

There are various methods through which we can calculate prime numbers upto n.

我们可以通过多种方法来计算最大为n的素数

1) General Method

1)一般方法

In this method, we usually run two for loops in which the First one is used to increase the number and the second one is used to check whether the number is prime or not. Second loop runs from 2 to ( n / 2 + 1 ) ( for better performance).

在这种方法中,我们通常运行两个for循环,其中第一个循环用于增加数字,第二个循环用于检查数字是否为质数。 第二个循环从2到(n / 2 +1)运行(以获得更好的性能)。

Note: This is the least efficient method (one should not use this if efficiency is required.)

注意:这是效率最低的方法(如果需要效率,则不应使用此方法。)

2) Square-Root Method

2)平方根法

In this method, two loops run first one is to increase the number and the second one is to check whether the number is prime or not. The second loop runs from 2 to square root (number) (a number which is to be check), that’s why the run length of second for loop is relatively small, that’s why it’s efficient than the naïve approach.

在此方法中,运行两个循环,第一个循环是增加数字,第二个循环是检查数字是否为质数。 第二个循环从2到平方根(数字)(要检查的数字),这就是为什么第二个for循环的运行长度相对较小的原因,这就是为什么它比幼稚的方法有效的原因。

3) Sieve of Eratosthenes

3)Eratosthenes筛

This is the best and most efficient method to calculate the prime numbers upto n.

这是计算最高达n的素数的最佳和最有效的方法。

Algorithm for Sieve of Eratosthenes:

Eratosthenes筛分算法:

  1. Let A be an array from 2 to n.

    设A为2到n的数组。

    Set all the values to

    将所有值设置为

    True (we are considering every number to be Prime)

    正确 (我们认为每个数字都是素数)

  2. For loop from p == 2 (smallest prime number)

    从p == 2开始的循环(最小质数)

  3. For loop from p2 to n

    从p 2到n的循环

    Mark all the multiples of

    标记所有的倍数

    p as False and increase the value of p to the next prime number

    数p作为假和增加p值到下一个素数

  4. End of second FOR loop

    第二个FOR循环结束

  5. End of first FOR loop

    第一个FOR循环结束

At the end of both the for loops, all the values that are marked as TRUE are primes and all the composite numbers are marked as FALSE in step 3.

在两个for循环的末尾,在步骤3中,所有标记为TRUE的值均为质数,所有复合数字均标记为FALSE。

Time complexity : O(n*log(log(n)))

时间复杂度:O(n * log(log(n)))

Note: Performance of General Method and SquareRoot Method can be increased a little bit if we check only ODD numbers because instead of 2 no even number is prime.

注意:如果只检查ODD数,则通用方法和SquareRoot方法的性能可以提高一点,因为不是2的偶数不是素数。

Example:

例:

from time import time
from math import sqrt
def general_approach(n):
'''
Generates all the prime numbers from 2 to n - 1.
n - 1 is the largest potential prime considered.
'''
start = time()
count = 0
for i in range(2, n):
flag = 0
x = i // 2 + 1
for j in range(2, x):
if i % j == 0:
flag = 1
break
if flag == 0:
count += 1
stop = time()
print("Count =", count, "Elapsed time:", stop - start, "seconds")
def count_primes_by_sqrt_method(n):
'''
Generates all the prime numbers from 2 to n - 1.
n - 1 is the largest potential prime considered.
'''
start = time()
count = 0
for val in range(2, n):
root = round(sqrt(val)) + 1
for trial_factor in range(2, root):
if val % trial_factor == 0:
break
else:
count += 1
stop = time()
print("Count =", count, "Elapsed time:", stop - start, "seconds")
def seive(n):
'''
Generates all the prime numbers from 2 to n - 1.
n - 1 is the largest potential prime considered.
Algorithm originally developed by Eratosthenes.
'''
start = time()
# Each position in the Boolean list indicates
# if the number of that position is not prime:
# false means "prime," and true means "composite."
# Initially all numbers are prime until proven otherwise
nonprimes = n * [False]
count = 0
nonprimes[0] = nonprimes[1] = True
for i in range(2, n):
if not nonprimes[i]:
count += 1
for j in range(2*i, n, i):
nonprimes[j] = True
stop = time()
print("Count =", count, "Elapsed time:", stop - start, "seconds")
# Time complexity : O(n*log(log(n)))
def main():
print("For N == 200000\n")
print('Sieve of Eratosthenes Method')
seive(200000)
print('\nSquare Root Method')
count_primes_by_sqrt_method(200000)
print('\nGeneral Approach')
general_approach(200000)
main()

Output

输出量

For N == 200000
Sieve of Eratosthenes Method
Count = 17984 Elapsed time: 0.050385475158691406 seconds
Square Root Method
Count = 17984 Elapsed time: 0.9392056465148926 seconds
General Approach
Count = 17984 Elapsed time: 101.83296346664429 seconds

翻译自: https://www.includehelp.com/python/calculate-prime-numbers-using-different-algorithms-upto-n-terms.aspx

python求素数算法

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/380822.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

cmd运行php文件以及环境配置出现的问题、 php.exe不是内部或外部命令,也不是可运行的程序 或批处理文件、PHP startup: Unable to load dynamic library

我用php.exe远行php文件出现了几个问题,先说一下怎么解决这些问题的,然后再说怎么运行 首先是出现 ‘php.exe’ 不是内部或外部命令,也不是可运行的程序 或批处理文件,查了一下,是没有配置php环境变量,配置php环境的过…

开启和关闭wifi的代码段

1、需要申请的权限android.permission.ACCESS_WIFI_STATE android.permission.CHANGE_WIFI_STATE android.permission.WAKE_LOCK 2、获取WifiManagerwifiManager (WifiManager) this.getSystemService(Context.WIFI_SERVICE); 3、开启、关闭wifiif (wifiManager.isWifiEnable…

java boolean例子_Java Field setBoolean()用法及代码示例

java.lang.reflect.Field的setBoolean()方法用于将字段的值设置为指定对象上的布尔值。当需要将对象的字段的值设置为布尔值时,可以使用此方法在对象上设置值。用法:public void setBoolean(Object obj, boolean z)throws IllegalArgumentException,IllegalAccessEx…

Python程序打印字符串,从字符串中提取字符

In this program – we are going to learn how can we complete string, print specific characters, print a range of the characters, print string multiple times (using * operator), print multiple stings by concatenating them etc. 在此程序中,我们将学…

php定义常量、判断有没有被定义、预定义常量、显示所有常量

常量一旦被定义,在脚本的其他任何地方都不能被改变,注意:常量名的前面没有$ 语法:define(name,value,case_insensitive ) name:常量名,一般常量名都大写value:常量值case_insensitive :bool类型…

Word——Word中粘贴Visio图只显示下面一部分

1. 问题发现 前段时间帮朋友整理一篇学位论文,发现在Word中粘贴画好的Visio图时,只能显示Visio图的下面一部分(一行宽左右)。通过:右键-->“设置图片格式”-“版式”-“环绕方式”-“嵌入型”,发现环绕方…

java server模式 设置_JVM client模式和Server模式的区别

这里向大家描述一下JVM client模式和Server模式两者的区别和联系,JVM如果不显式指定是-Server模式还是-client模式,JVM能够根据下列原则进行自动判断(适用于Java5版本或者Java以上版本)。JVM client模式和Server模式JVM Server模式与client模式启动&…

python 整数 1字节_Python程序打印代表整数的字节数组

python 整数 1字节Given an integer number and we have to convert it into a byte array in Python. 给定一个整数,我们必须在Python中将其转换为字节数组。 To convert an integer number into bytes (byte array), we use to_bytes() method of int class, it …

PHP的数据类型、浮点型比较

在介绍php的数据类型前,先说一说强数据类型和弱数据类型。 弱数据类型:变量的类型取决于存放值的类型 强数据类型:变量的类型取决于申明变量时的类型。比如申明变量是A类型就不能存放B类型 PHP是弱数据类型,php支持8种原始数据类型…

《测试驱动开发》读书笔记

最终目标是整洁可用的代码 我们不是从建立对象开始,而是从测试开始 了解需求-》设计测试 -》让测试通过 列出所有已知问题,然后一个一个解决; 培养将软件开发化为一小步一小步开发任务的能力 测试程序与代码所存在的问题不在于重复设计&#…

java sampling_Java机器学习库ML之三Sampling(采样)

场景:从样本集中采样80%用于训练,20%用于验证。参考代码如下:package com.gddx;import java.io.File;import java.util.Map;import libsvm.LibSVM;import net.sf.javaml.classification.Classifier;import net.sf.javaml.classification.eval…

puppeteer api_使用Node.js和Puppeteer API生成PDF文件

puppeteer apiPuppeteer is a Node library developed by Google and provides a high-level API for developers. Puppeteer是Google开发的Node库,并为开发人员提供了高级API。 With Node.js already up and running, we will install puppeteer via NPM (node pa…

php中进制转换

我们知道,进制有二进制、八进制、十进制、十六进制,但在php中只能存取八进制、十进制、十六进制 在讲进制转换之前,我们先说一下进制单词的缩写: 二进制:bin八进制:oct十进制:dec十六进制&…

java canvas画圆圈_java – 在视图上绘制一个圆圈(android)

几点意见:在确定圆的中心点和半径时,您需要考虑分配给视图的宽度和高度.您应该考虑分配给视图的填充,这样就不会绘制该保留部分.你应该避免在onDraw方法中分配对象,因为这会被调用很多.为了允许在XML布局中指定视图,您需要提供带有Context和AttributeSet的构造函数.…

第七章:项目成本管理

项目成本管理包括对成本进行估算、预算和控制的各过程,从而确保项目在批准的预算内完工。其包括 估算成本:对完成项目活动所需资金进行近似估算的过程制定预算:汇总所有单个活动或工作包的估算成本,建立一个经批准的成本基准的过程…

python rgb 图像_在Python中查找RGB图像的互补图像

python rgb 图像Complementary image is a transformed image such that it consists of complementary colours of the ones, which is present in the original image. 互补图像是一种变换后的图像 ,它由原始图像中存在的互补色组成。 For finding the complemen…

php的字符串、双引号输出变量的问题、转义字符

字符串 php中字符串可以用单引号和双引号表示&#xff0c;但单引号效率比双引号高&#xff0c;因为单引号是真正的字符串&#xff0c;双引号要做运算&#xff0c;即将字符串中的变量替换成值&#xff0c;单引号不需要 看下面的例子 <?phpheader(content-type:text/html;…

jmeter从mysql取值_Jmeter获取数据库值并作为参数请求(转载)

转载自&#xff1a;https://www.cnblogs.com/mawenqiangios/p/11088672.html01Jmeter连接数据库1、添加JDBC Connection Configuration(右键测试计划-->配置元件-->JDBC Connection Configuration)2、配置数据库连接信息&#xff0c;其中DataBase URL&#xff1a;jdbc:my…

圣斗士星矢

一部漏洞百出&#xff0c;情节重复&#xff0c;对白肉麻啰唆&#xff0c;人物刻画单一的动漫绵延了近二十年80一代的情结&#xff0c;每一个人都曾用稚嫩的声音&#xff0c;以“庐山升龙霸”抑或是“凤翼天翔”怒吼&#xff0c;今天&#xff0c;讨论的问题是&#xff1a;他&…

用于将类型从double转换为int的C#程序

Given a double type of variable, we have to convert it into an integer in C#. 给定双重类型的变量&#xff0c;我们必须在C&#xff03;中将其转换为整数。 Syntax: 句法&#xff1a; int_variable (int)double_variable;Example: 例&#xff1a; Input:double a 123…