简体   繁体   中英

How to check whether a number is prime or not and ask the user again if it's not prime without exiting the program?

I'm trying to check whether a number is prime or not as a part of Diffie Hellman algorithm and if it's not a prime number ask the user again to input another number without exiting the program.

Here's my code:

def prime(p):
    for i in range(2,p):
        if (p % i) == 0:
            return(False)
            break
        else:
            return(True)


    def primRoots(p):
        roots = []
        required_set = set(num for num in range (1, p))

        for g in range(1, p):
            actual_set = set(pow(g, powers) % p for powers in range (1, p))
            if required_set == actual_set:
                roots.append(g)           
        return roots

    p=int(input("enter any prime no:"))
    check=prime(p)
    if(check==True):

        primitive_roots = primRoots(p)

        g=primitive_roots[0]
        print(g)
        x=int(input("Alice chooses value of X as:"))
        y=int(input("Bob chooses value of y as:"))
        r1=(g**x) % p
        r2=(g**y) % p

        print("value of r1 is",r1)
        print("value of r2 is",r2)

        a=x*y

        k1=(r2**x) % p
        print("k1 is",k1)
        k2=(r1**y)% p
        print("k2 is",k2)
        k=(g**a)%p
        print("shared key is",k)    
    else:
        print("It is not a prime num,enter again")
        prime(p)
user_input = int(input("Enter an integer !  "))

def prime(n):
    isPrime = True
    for num in range(2, int(n/2)):
        if n % num == 0:
            isPrime = False
    return isPrime


while (prime(user_input)== False):
    user_input = int(input("==> Your input is incorrect, please enter  an other integer !"))
print("{} is prime ".format(user_input))

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM