此python代码在代码的随机数生成器部分返回ValueError
。我在函数中使用硬编码值运行它:def fermat_test(n):
at the line
a = random.randit(2,n-1)
,似乎不然。我无法弄清楚为什么范围超出范围?
import random
def remainder(i,j):
rem = i%j
return rem
def is_even(n): return n % 2 == 0
def square(n): return n**2
def expmod(b, e, m):
if e==0:
return 1
elif is_even(e):
expm = expmod(b, e/2,m)
return remainder(expm*expm,m)
else:
return remainder(b*expmod(b,e-1,m),m)
def fermat_test(n):
a = random.randint(2,n-1)
return expmod(a,n,n)==a
def is_fermat_prime(n, ntimes):
if ntimes == 0:
return True
elif fermat_test(n):
return is_fermat_prime(n,ntimes-1)
else:
return False
## this is the test you can use to test your code
def sum_of_fermat_primes(n):
sum = 0
for i in xrange(n+1):
if is_fermat_prime(i, 70):
sum += i
return sum
print sum_of_fermat_primes(10)
print sum_of_fermat_primes(20)
print sum_of_fermat_primes(560)
print sum_of_fermat_primes(570)
Traceback (most recent call last):
File "C:\Users\Terik\.atom\code.py", line 33, in <module>
print sum_of_fermat_primes(10)
File "C:\Users\Terik\.atom\code.py", line 30, in sum_of_fermat_primes
if is_fermat_prime(i, 70):
File "C:\Users\Terik\.atom\code.py", line 22, in is_fermat_prime
elif fermat_test(n):
File "C:\Users\Terik\.atom\code.py", line 17, in fermat_test
a = random.randint(2,n-1)
File "C:\Python27\lib\random.py", line 242, in randint
return self.randrange(a, b+1)
File "C:\Python27\lib\random.py", line 218, in randrange
raise ValueError, "empty range for randrange() (%d,%d, %d)" % (istart, istop, width)
ValueError: empty range for randrange() (2,0, -2)
答案 0 :(得分:3)
错误是因为
a = random.randint(2,n-1)
n - 1
小于2
。事实上,n
的值来自i
中的for i in xrange(n+1)
,因此它从0
,1
,2
等开始。最小值会导致random.randint(2,n-1)
无效。