[英]checking if something is a prime python?
def prime_check(num):
if num>1:
if num == 2:
return True
for i in range(2, num+1):
if ((num%i) == 0):
print(i)
return False
else:
return True
else:
return False
prime_check(99)
returns true
(as in is prime) when it should be false when i use value 99. WHY?当我使用值 99 时它应该为 false 时
returns true
(如素数)。为什么?
In the loop, you're returning true whenever the input is not divisible by the current number in the loop.在循环中,只要输入不能被循环中的当前数字整除,您就会返回 true。 So, in the first iteration, when
if
condition checks whether 99%2 == 0, if so then return false
else return true
.因此,在第一次迭代中,当
if
条件检查 99%2 == 0 时,如果是则返回false
否则返回true
。 That's why it returns True
as 99%2 != 0
.这就是为什么它返回
True
为99%2 != 0
。
Just change your code a bit, as you are using for....else
:只需稍微更改您的代码,就像您使用
for....else
:
if (num >1):
for i in range(2, num):
if ((num%i) == 0):
print(i)
return False
else:
return True
You can improve the program by decreasing the range of the loop using range(2,math.floor(math.sqrt(num)))
:您可以通过使用
range(2,math.floor(math.sqrt(num)))
减少循环range(2,math.floor(math.sqrt(num)))
来改进程序:
for i in range(2,math.floor(math.sqrt(num))):
//do the same
When 99 enters into the for loop It checks whether 99%2==0
, as it finds 99%2!=0
else
block is executed, returns true
and comes out of the loop without doing further iterations.当 99 进入 for 循环时,它检查是否
99%2==0
,因为它发现99%2!=0
else
块被执行,返回true
并退出循环而不做进一步的迭代。 You need to change the code.您需要更改代码。
To reduce the complexity you can further use sqrt functions.为了降低复杂性,您可以进一步使用 sqrt 函数。 You can refer to this
你可以参考这个
def prime(num):
if num==1:
return False
else:
for i in range(2,num):
if num%i==0:
return False
return True
print(prime(17))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.