将函数的结果存储为变量

时间:2016-07-28 02:17:26

标签: python rsa

我正在尝试编写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,但他们只是给我一个错误。我意识到我需要做一些回报,但我无法正确理解

2 个答案:

答案 0 :(得分:3)

只需将print '%i' %a替换为return a

答案 1 :(得分:0)

我认为您的check_if_primeget_a_prime功能都存在错误。在前者中,ZZ未定义,第一个break应缩进一个级别,最后一个级别是多余的。更好的是,只需在需要时返回真或假。

在第二个函数中,您需要返回素数而不是仅打印它。

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
相关问题