Oni*_*lol 2 python for-loop if-statement range
我正在尝试根据以下方式编写素数检查器:Prime方程式
到目前为止,我的代码如下所示:
def primer(x):
prime = False
x = math.sqrt(x)
if type(x) == float:
x = math.ceil(x)
for i in range(3,x + 1):
if (i % 2) == 1:
prime == True
print(prime)
Run Code Online (Sandbox Code Playgroud)
尝试使用37作为primer(37)---> sqrt(37)是6.08
四舍五入到7
7 mod 3 = 1(素数)
我不知道primevar没有更新.有人可以点光吗?
编辑:链接一些repl - > Repl Link
你实际上并没有分配:
prime == True
Run Code Online (Sandbox Code Playgroud)
应该:
prime = True
Run Code Online (Sandbox Code Playgroud)
==是一个比较运算符,=用于赋值.
您可以使用该any函数创建素数检查器,我们只需要循环到x的sqrt并检查奇数.我还添加了fermat的小定理的实现,链接中提到了:
def primer(x):
if x == 2:
return True
if x % 2 == 0 or x < 3:
return False
return not any(x % i == 0 for i in range(3, int(x ** .5) + 1, 2))
from random import randint
def fermat_little_theorem(p, conf):
"""
int p to test if prime
conf is the confidence level/how many times to try n ** (p - 1) % p == 1
returns with confidence p is prime based on 1/2^conf
"""
if p <= 1:
return False
for _ in range(conf):
n = randint(1, p - 1)
if not n ** (p - 1) % p == 1:
return False
return True
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
56 次 |
| 最近记录: |