Search code examples
pythonprimes

function to check if a number is prime not giving output


I am trying to write a function for checking if a number is prime or not and have written the below function. But though the function doesnt throw an error upon defining it , it doesnt execute when run with an input argument ( like say 23) . Have tried running it on Jupyter notebook where the kernel keeps running , as well as an online editor where i get the error "Error: Command failed: timeout 7 python3". Am unable to see possible issues such as division with 0 etc.Could you please help ?

def prime_check(num):
    
    prime =True
    while prime==True:
        for i in range(2,num):
            if num%i ==0:
                prime=False
                break
    return prime

Solution

  • Think what happens in your code when you have prime. It never exit from while loop.

    This could work

    def prime_check(num):
      for i in range(2,num):
        if num%i == 0:
           return False
      return True
    

    And there is lot of things you can do to optimize your code. It is good training to improve your algorithm. Nice combination of math and coding.

    We know that 3227873423 is a prime. Try to run your code like this.

    import time
    def timer():
        start_time = time.time()
        prime_check(3227873423)
        end_time = time.time()
        return end_time-start_time
    
    timer()
    

    This returns time in seconds your code needed to do the test. You can improve your code and see how much faster you can get it. Don't forget to test that it returns right results also after optimization.

    And you can get big primes for testing from here: https://bigprimes.org/