Problem with following python code
Dick Moores
rdm at rcblue.com
Tue Jun 12 01:36:30 EDT 2007
At 09:52 PM 6/11/2007, Dan Hipschman wrote:
>On Tue, Jun 12, 2007 at 04:25:31AM -0000, why? wrote:
> > I've been having problem with the following code. It's supposed to
> > print the prime numbers between 10 and 100. But i'm not getting any
> > output, i.e. i guess the outer 'for' loop is being traversed only
> > once. I would be greatful if you could help me out. Thanx!
> > >>> f=1
> > >>> for i in range(10,100):
> > ... for j in range(2,i):
> > ... if i%j==0:
> > ... f=0
> > ... break
> > ... else: continue
> > ... if f==1:
> > ... print i,
> > ...
>
>Move "f=1" inside the outer loop:
>
>for i in range(10,100):
> f=1
> for j in range(2,i):
> if i%j==0:
> f=0
> break
> else: continue
> if f==1:
> print i,
>
>It gets set to 0 in the first iteration and never has another chance to
>be set to 1 after that.
And of course the inner loop does too much work. Try:
for i in range(10,100):
f=1
max = int(i**.5 + 1)
for j in range(2,max):
if i%j==0:
f=0
break
else: continue
if f==1:
print i,
Dick Moores
More information about the Python-list
mailing list