查找素数以排序循环条件 [英] Find prime number to sortest loop condition

查看:83
本文介绍了查找素数以排序循环条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手.当我在循环条件下学习时,我得到下面给出的质数代码

I'm newbie in Python. When I study in loop condition, I got code for prime number given below

i = 13
j = 2
while(j <= (i/j)):
 if not(i%j): break
 j = j + 1
 if (j > i/j) : print i, " is prime"

在这里,我希望逻辑在条件成立时中断,如果要查找13是素数,我们使用的循环范围是2到12. 在这里,由于循环条件while(j <= (i/j)),他们仅使用了3个循环. 循环结构为

Here I want logical to break while condition, if we want to find 13 is prime number or not we used loop range is 2 to 12. Here they used only 3 loop because of the loop condition while(j <= (i/j)). The loop structure is

 i  ==>  j  while(j <= (i/j))
 13      2  2<=6(13/2) true
 13      3  3<=4(13/3) true
 13      4  4<=3(13/4) false

我的问题是,4<=3(13/4)满足循环的条件如何检查素数?

My question is, how the condition 4<=3(13/4) to satisfy the loop to check prime number?

我希望数学逻辑对任何人都可以帮我清楚的解释.

I want maths logical any one help me the clear explanation.

推荐答案

此处重要的一点是要注意,如果ij = n,则i,j中的至少一个小于或等于sqrt(n).因此,我们只需要检查不超过sqrt(n)的因子.因此,要测试25是否为质数,我们需要测试不超过5的因数.要测试23,我们需要循环测试2、3和4,然后当我们达到5时,我们注意到我们> sqrt (23)和休息.测试j> i/j是相同的测试,因为j> i/j表示j ^ 2> i.

The important thing here is to note that if ij = n, then at least one of i, j is less than or equal to sqrt(n). Therefore, we only need to check factors up to and including sqrt(n). So to test whether 25 is prime, we need to test factors up to 5. To test 23, we would need to loop and test 2, 3, and 4, and then when we get to 5 we notice that we're > sqrt(23) and break. The test j > i/j is the same test, since j > i/j implies that j^2 > i.

这篇关于查找素数以排序循环条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆