【问题标题】:Sage (Python) Math Programming, Writing an Algorithm to check for PrimalitySage (Python) 数学编程,编写算法来检查素数
【发布时间】:2016-11-03 09:19:00
【问题描述】:

我需要在 Sage 中编写一个代码来解决家庭作业问题,通过将其除以小于或等于 10^4 的所有已知素数来检查在 10^7 和 10^8 之间生成的随机数是否是素数。在此之前,我从未在 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() 会检查一个数字是否是素数,但我们特别应该做这个“天真的”检查素数。 如果有人可以帮助我解决这个问题,我将不胜感激。

【问题讨论】:

  • 给定n < 10^410^7 <= random_x < 10^8,那么n % random_x 总是n,因为n < random_x。我想你的意思是x = random_between(10**7, 10**8); if x % n == 0: ...

标签: python primes sage number-theory


【解决方案1】:

你的 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 2021-01-12
    • 1970-01-01
    • 2016-10-30
    • 1970-01-01
    • 2019-09-13
    相关资源
    最近更新 更多