簡體   English   中英

將函數的結果存儲為變量

[英]Store the result of a function as a variable

我正在嘗試編寫RSA代碼,但遇到了一件簡單的事情。 我想將函數的結果存儲為變量,在Python中兩次。 這是我的代碼

def random_odd_between(j,k):
    k1 = (k-1)//2
    j1 = j//2
    a1 = int(random()*(k1-j1+1))+j1
    a = 2*a1 +1
    return a

# The list of primes less than 10^6 is given by:
list_of_primes = prime_range(1,10^6)

# Write a function to check if given number is prime:
def check_if_prime(n):
    prime_flag = 1
    for i in list_of_primes:
        checker = n%i
        if checker != 0:
            if (n/i) in ZZ:
                prime_flag = 0
        break
    else:
        prime_flag = 0
        break
    return prime_flag

# Generate random numbers between 6*10^9 and 10^10 until we get a prime.
# Generate two prime numbers between 6*10^9 and 10^10 for p and q
def get_a_prime():
    count = 0
    prime_found = 0
    while prime_found == 0:
        a = random_odd_between(6*10^9,10^10)
        prime_found = check_if_prime(a)
        count = count + 1
# Print a prime you've got:
    print '%i' %a

p = get_a_prime()
q = get_a_prime()
n = p*q

# Let t stand for totient

t = (p-1)*(q-1)

我無法定義我的p和q,但是它們一直給我一個錯誤。 我意識到我需要進行某種返回,但是我無法正確獲取語法

只需將print '%i' %a替換為return a

我相信您的check_if_primeget_a_prime函數都出錯。 在前者中,沒有定義ZZ ,應該將第一個break縮進一個級別,而最后一個則是多余的。 更好的是,僅在需要時返回True或False。

在第二個函數中,您需要返回素數的值,而不僅僅是打印它。

def check_if_prime(n):
    if n == 2:
        return True  # 2 is a prime.
    if n % 2 == 0 or n <= 1:
        return False  # Anything less than or equal to one is not prime.

    for divisor in xrange(3, int(n ** 0.5) + 1, 2):  # 3, 5, 7, ..., int(SQRT(n)) + 1
        if not n % divisor:  
            return False  # NOT divisible by the divisor.

    return True  # Must be prime.

def get_a_prime():
    prime_found = False
    while not prime_found:
        a = random_odd_between(6 * 10 ^ 9, 10 ^ 10)
        prime_found = check_if_prime(a)
    return a

測試

primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101]

# Ensure all primes above are prime per our function.
>>> all(check_if_prime(n) for n in primes)
True

# Ensure all numbers in range 0-101 that is not identified as a prime is not a prime.
>>> any(check_if_prime(n) for n in xrange(102) if n not in primes)
False

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM