+ 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")
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
+ 14
You forgotten to increment i and j in your loops, leading to infinite iterations.
+ 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 ;)
"""
+ 2
thanks so much u solve my problem đ
+ 1
can u tell me the code
0
Error:Infinite iterations
- 1
you forgot to increment i by one