+ 1
Why doesn't it work properly?
I created a code to response whether a number is prime or not , but it doesn't work ... why? n = int(input()) i = 1 check = True while i<n: i=i+1 if(n%i==0): check = False else: continue print(check)
6 Respostas
+ 3
You can see what happend when you test your code here on SL Playground with a print statement or anywhere with a debugger. Here an example how it can be done:
n = int(input())
i = 2
check = True
while i<n:
print(n%i)
if(n%i==0):
check = False
break
i=i+1
print(check)
+ 1
Angelo of course at the first time , I incremented i , in the end of while loop , and because in that case the loop never ends(dont know how to fix it when using the increment in the end of loop) , so I decided to delcare the increment in the first line of loop block . Now I just changed i value to 2 , and removed 'continue' part , should I do anything else ? Bcz I see the same result .
+ 1
JaScript got it...thank you.
+ 1
Ali_combination the reason the loop never ended was because 'continue' makes the loop start the next cycle without executing what's under it (in your case the increment)
0
Let's say n=3
1<3 i=2 2%3!=0
2<3 i=3 3%3==0
Did you see the problem?
Try starting with i=2 and increment it after every check
Also, you don't need that
else: continue
So get rid of it
After you fixed your code you can start thinking of optimization, for example you don't need to check for i>sqrt(n)
0
Angelo true👍... and I think my most important mistake was either excluding or including indentation ... it's always a headache ...