[英]Random Number Range in Python, ValueError: empty for Range ()
This python code is returning a ValueError
in the random number generator section of the code. 此python代码在代码的随机数生成器部分返回ValueError
。 I ran it with hardcoded values in the function: def fermat_test(n):
at line a = random.randit(2,n-1)
, and it seemed to run otherwise. 我使用函数中的硬编码值运行它: def fermat_test(n):
在a = random.randit(2,n-1)
,它似乎以其他方式运行。 I can't figure out why the range is out of bounds? 我不知道为什么范围超出范围?
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)
The error is because in 错误是因为
a = random.randint(2,n-1)
n - 1
is less than 2
. n - 1
小于2
。 In fact, the value of n
comes from i
in for i in xrange(n+1)
, so it starts from 0
, 1
, 2
, etc. These smallest values make the random.randint(2,n-1)
invalid. 实际上,的值n
来自i
在for i in xrange(n+1)
所以它从开始0
, 1
, 2
,等,这些最小值使random.randint(2,n-1)
无效。
您在xrange中的i从0开始,应该从1开始。
for i in xrange(1, n+1):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.