我需要在Sage中编写一个代码,用于检查在10 ^ 7和10 ^ 8之间生成的随机数是否为素数,将其除以所有小于或等于10 ^ 4的已知素数。在此之前,我从未在Sage中编程作为警告。这是我到目前为止所做的。
# This creates a function to create a random number between two numbers
def random_between(j,k):
a=int(random()*(k-j+1))+j
return a
# Testing that the function works, which it does, though I don't know how
# to assign a variable to it like x=random_between(10^7,10^8)
random_between(10^7,10^8)
# The list of primes less than 10^4 is given by
list_of_primes = prime_range(1,10^4)
# Want to write a function to check if prime
def check_if_prime(n):
for n in list_of_primes:
if n % random_between(10^7,10^8)==0:
print 'number is prime'
else
print 'number is not prime'
我想要做的是确定list_of_primes
中的数字是否使用random_between
命令划分%
生成的随机数,然后打印number x is a prime
或者说不是。
我知道命令Primes()
将检查一个数字是否为素数,但我们特别应该这样做“天真”检查素数。
如果有人可以帮助我,我会非常感激。
答案 0 :(得分:0)
你check_if_prime
函数可以使用一些工作。我在下面重写了。
def check_if_prime(): # there's no parameter for this method since we're checking against the global var list_of_primes
for n in list_of_primes:
if random_between(10^7,10^8) % n == 0: # if a random number / a prime number has no remainder, the random number is not prime
print 'number is not prime'
return # we're done, we know it's not prime
print 'number is prime' # we made it through all of our tests, the number might be prime