1

Following is the code to generate prime nos:

to_num=int(raw_input("Enter till where u wish to generate prime nos > "))

i=2
flag="prime"
j=2
while i <= to_num:

 while j<i:

  if i%j == 0:
   flag="nprime"
   break
  else:
   flag="prime"


 if flag=="prime":
  print "%d is  prime"%i


  j+=1
 i+=1

However the result produced isnt as expected, e.g:

Enter till where u wish to generate prime nos > 10
2 is  prime
3 is  prime
4 is  prime
5 is  prime
6 is  prime
7 is  prime
8 is  prime
9 is  prime
10 is  prime

Could you please guide me as to where i am going wrong?

P.S: The desired results are obtained using for loop.

Bakuriu
  • 98,325
  • 22
  • 197
  • 231
abhishek nair
  • 324
  • 1
  • 6
  • 18

2 Answers2

3

Your for loops looked like this:

for i in range(2, to_num+1):
    for j in range(2, i):
        …

But your while loops look like this:

i = 2
j = 2
while i <= to_num:
    while j < i:
        …
        j += 1
    i += 1

So you never reset j back to 2 after the loop completes. You should add a j = 2 at the beginning of the outer loop in order to make the while loops equivalent to the for loops:

i = 2
while i <= to_num:
    j = 2
    while j < i:
        …
        j += 1
    i += 1

Finally note, that you want to increment j in every iteration. In the code in your question, you have the j += 1 as part of the if flag=="prime":, so it would only increment j for primes. Instead, you need to move the increment up into the while loop:

i = 2
while i <= to_num:
    j = 2
    while j < i:
        # the prime check here
        j += 1

    if flag == "prime":
        print "%d is  prime" % i

    i += 1

I would really suggest you to use a bigger indentation than a single space in order to see these issues yourself. They are hard to spot when everything is indented so similarly.

poke
  • 369,085
  • 72
  • 557
  • 602
0

You need to reset your inner flags and counters:

to_num=100

i=2
is_prime=False
j=2
while i <= to_num:
 is_prime=True // you need to reset your inner flags
 j=2 // set j to starting value
 while j<i:

  if i%j == 0:
   is_prime=False
   break

  j+=1

 if is_prime==True:
   print (i)

 i+=1

It's also better to use boolean flag, instead of string. It's more readable, and you don;t need to bother about the String.

Beri
  • 11,470
  • 4
  • 35
  • 57