Python脚本查找第n个质数

编程入门 行业动态 更新时间:2024-10-19 02:14:37
本文介绍了Python脚本查找第n个质数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我是Python的新手,我想我会尝试通过编写一个函数来找到第n个素数来学习一些技巧,但是我无法使我的代码正常工作.毫无疑问,这是由于我遗漏了一些基本知识,但是我很感谢您在发现错误之处方面的帮助!

I'm new to Python and I thought I'd try to learn the ropes a bit by writing a function to find the nth prime number, however I can't get my code to work properly. No doubt this is due to me missing something fundamental, but I'd appreciate your help in finding where it went wrong!

c=2 n=input("Which prime would you like? ") n=int(n) a=[] l=len(a) while l<=n: if c==2: a.append(c) elif (c % 2 ==0): #c is even break elif (c % 2 !=0): #c is odd if c<7: a.append(c) elif c >=7: for i in range(3,int((c+1)/2)): if (c % i ==0): break else: a.append(c) else: c+=1 a[n]

谢谢! 安德鲁

推荐答案

这可以是一个开始.这将检查数字N是否可被2至int(sqrt(N)) + 1的所有数字整除,其中int函数将截断N的平方根.如果列表中的所有成员,python中的all()函数将返回True满足一些条件(此处不为零).您应该设置一个上限,因为对于很大的n来说这不是很有效.我把它留给你.

This can be a start. This checks whether the number N is divisible by all numbers from 2 to int(sqrt(N)) + 1, where the int function truncates the square root of N. The all() function in python returns True if all members of a list satisfy some condition (here not zero). You should set an upper bound as this is not very efficient for really large n. I'll leave that to you.

def nthprime(n): import math start = 2 count = 0 while True: if all([start % i for i in range(2, int(math.sqrt(start)) + 1)]) != 0: count += 1 if count == n: return start start += 1 In [91]: nthprime(50) Out[91]: 229 In [92]: nthprime(100) Out[92]: 541

使用此进行了测试.

更多推荐

Python脚本查找第n个质数

本文发布于:2023-11-30 04:31:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648734.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:质数   脚本   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!