I'm trying to write an RSA code, but I'm having issues with a simple thing. I want to store the result of a function as a variable, twice in Python. This is my code
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)
I can't get my p and q to be defined however, they keep just giving me an error. I realize I need to do some kind of return, but I can't get the syntax right
只需将print '%i' %a
替换为return a
I believe you had errors in both your check_if_prime
and get_a_prime
functions. In the former, ZZ
is not defined and the first break
should be indented one more level and the last one is redundant. Better yet, just return True or False when needed.
In the second function, you need to return the value that is prime rather than just print it.
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
Testing
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.