0

No output in my code

i tried making a primality test, i tried to input 237028843(this is a prime) but there is no output here's the code : p = int(input()) if p < 2 : print(p, 'is not a prime') print(' ') print('No prime number is less than 2') r = p//2 if r % 2 == 0 : r+= 1 if p > 1 : for n in range(3, r+1, 2) : if p % 2 == 0 and p != 2 : print(p, 'is not a prime') print(' ') print(p, 'is 2*'+str(p//2)) break elif p == 2 : print(p, 'is a prime') break if p % n == 0 : print(p, 'is not a prime') print(' ') print(p, 'is '+str(n)+'*'+str(p//n)) break else : if p > 1 : print(p, 'is a prime') can someone tell me why is there no output in my code

23rd Jan 2023, 2:21 AM
Valent Inkiriwang
Valent Inkiriwang - avatar
3 Respuestas
+ 3
Valent Inkiriwang Running your code on large numbers seems to result in an "Execution Timed Out!" error. This can be shown by adding a `print(n)` at the start of the loop. Not entirely sure how or why this happens, but it seems to be because the loop executes the same few lines of code too many times without an output: https://www.sololearn.com/discuss/2076661/?ref=app This can be fixed with some simple optimizing: 1) The part of the loop that tests for p==2 and p%2==0 can be taken out of the loop and into the top level of the code, since these conditions don't depend on n. 2) Instead of testing for divisibility of n up to r=p//2, you can test up to r=math.sqrt(p) to further reduce the number of iterations. https://en.m.wikipedia.org/wiki/Primality_test Hope this helps :)
23rd Jan 2023, 5:10 AM
Mozzy
Mozzy - avatar
+ 2
# Hi ,Valent Inkiriwang, you can take a look at this one: def isPrime(n): """isPrime(n): int -> None""" if n < 2 or (n > 2 and (n % 2) == 0): print(n, "is not a prime!") elif n in [2, 3]: print(n, "is a prime!") else: for i in range(3, n, 2): if n % i == 0: print(n, "is not a prime!") break elif i > n ** (1/2): print(n, "is a prime!") break n = 237028843 isPrime(n)
23rd Jan 2023, 12:05 PM
Per Bratthammar
Per Bratthammar - avatar
+ 1
your code works well. however, you need to optimize it to do things better because 237028843 is a large number and your code processes a lot of steps my suggest code: from math import sqrt def isPrime(p): if p<2 or p%2==0: return False if p==2 or p==3: return True for i in range(3, int(sqrt(p)+1), 2): if p%i==0: return False return True
25th Aug 2023, 6:27 PM
Han Tong
Han Tong - avatar