Bridge
Bridge

Reputation: 105

Incorrect behaviour in program that calculates prime numbers

This program insists that 35 is a prime number even though, going through it step-by-step, the program should reach the point where it calculates 35%5 and then ignore the number (because the result is 0.) I haven't checked every single number but it seems to display only primes otherwise (except for numbers that are anologous to 35 like 135.)

print ('How many prime numbers do you require?')
primes = io.read("*n")

print ('Here you go:')

num,denom,num_primes=2,2,0

while num_primes<primes do
   if denom<num then
      if num%denom==0 then
         num=num+1
      else
         denom=denom+1
      end
   else
      print(num)
      num=num+1
      num_primes=num_primes+1
      denom=2
   end
end

Sample output:

  How many prime numbers do you require?
  50
  Here you go:
  2
  3
  5
  7
  11
  13
  17
  19
  23
  27
  29
  31
  35
  37
  41
  43
  47
  53
  59
  61
  67
  71
  73
  79
  83
  87
  89
  95
  97
  101
  103
  107
  109
  113
  119
  123
  127
  131
  135
  137
  139
  143
  147
  149
  151
  157
  163
  167
  173
  179

Upvotes: 0

Views: 56

Answers (2)

Prasanth Louis
Prasanth Louis

Reputation: 5066

Fixed it, set denom=2 after num=num+1

    print ('How many prime numbers do you require?')
primes = io.read("*n")

print ('Here you go:')

num,denom,num_primes=2,2,0

while num_primes<primes do
   if denom<num then
      if num%denom==0 then
         num=num+1
         denom=2
      else
         denom=denom+1
      end
   else
      print(num)
      num=num+1
      num_primes=num_primes+1
      denom=2
   end
end

Upvotes: 0

Etan Reisner
Etan Reisner

Reputation: 81012

You aren't resetting denom in the % case.

if num%denom==0 then
    num=num+1
else

So when you fall-through this test you start testing the next number starting from the previous denominator instead of from 2 again.

Simple debugging print lines in the loop printing out denom and num would have shown this to you (as, in fact, that's exactly how I found it). You only need to three prime numbers output to see the issue.

Upvotes: 2

Related Questions