0

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
Jan
  • 42,290
  • 8
  • 54
  • 79
  • 1
    Does this answer your question? [Check if number is prime number](https://stackoverflow.com/questions/15743192/check-if-number-is-prime-number) – nikeros Dec 02 '21 at 11:35
  • Really, a short search for `prime` and `python` here would have yielded dozens of results. – Jan Dec 02 '21 at 11:36
  • But question here was why coded ended to infinity loop. Yes, internet is full of fine code examples how you can find primes. But still many of us has done this kind of programs when training to code. – ex4 Dec 02 '21 at 11:43

2 Answers2

1

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/

ex4
  • 2,289
  • 1
  • 14
  • 21
0
while prime==True: # if a prime is True this loop will continue forever
    for i in range(2,num):
        if num%i ==0:
            prime=False
            break

I'd recommend leaving the while prime == True: part out

Joeri
  • 626
  • 5
  • 18