+ 1

How to solve this? The output is "time limit exceeded"

num = 10 i = 2 while i <= num: j = 2 while j <= i: if i % j == 0: break if i == j: print(i,"is prime")

28th Apr 2017, 7:37 AM
Ridha Abdillah
Ridha Abdillah - avatar
7 Answers
+ 13
# There, this should be what you want. i = 2 while i <= 10: prime = True j = 2 while j < i: if i % j == 0: prime = False j+=1 if prime: print(i,"is prime") i+=1
28th Apr 2017, 7:49 AM
Hatsy Rei
Hatsy Rei - avatar
+ 14
You forgotten to increment i and j in your loops, leading to infinite iterations.
28th Apr 2017, 7:38 AM
Hatsy Rei
Hatsy Rei - avatar
+ 3
""" You can improve speed of your code by limiting your second 'while' loop to test j <= math.sqrt(i) ( store it outside the loop scope to avoid calculte it at each iteration ;) )... as if you have not find a divisor before, you don't find one after because multiplication is commutative ( a * b == b * a ) ^^ """ import math i = 2 while i <= 10: prime = True si = math.sqrt(i) j = 2 while j <= si: if i % j == 0: prime = False j+=1 if prime: print(i,"is prime") i+=1 """ Anyway, if you have to test if many numbers ar prime numbers, speed will also be improve by storing already tested prime numbers, and only test division by them ;) """
28th Apr 2017, 11:19 AM
visph
visph - avatar
+ 2
thanks so much u solve my problem 😃
28th Apr 2017, 7:52 AM
Ridha Abdillah
Ridha Abdillah - avatar
+ 1
can u tell me the code
28th Apr 2017, 7:39 AM
Ridha Abdillah
Ridha Abdillah - avatar
0
Error:Infinite iterations
28th Apr 2017, 10:28 AM
mei
mei - avatar
- 1
you forgot to increment i by one
19th Apr 2018, 9:31 AM
mei
mei - avatar