-2

I want to make a program in fortran that lists all the pairs of twin prime numbers in a range, n1 to n2, given by the user. I did this, but it doesn't work and I don't know how to fix it:

    implicit none
    integer n1, n2, p1, p2, i, j, k, m
    read(5,*) n1
    read(5,*) n2
    do i = n1, n2
      do m = i, n2
         do j = 2,(i-1)
             if (mod(i,j) /= 0) then
               p1 = i
           do k = 2, (m-1)
               if (mod(m,k) /= 0) then
                  p2 = m 
                   if (p2-p1 == 2) then
                      write(6,*) p1, p2
                   end if
               end if
           end do
             end if
         end do
      end do
    end do
    end

If I put the range 1 to 10, it print several pairs of 8 and 10.

Carmn
  • 5
  • 1
  • 1
    Is this a homework assignment? We *just* saw the same question: http://stackoverflow.com/questions/42882840/how-find-a-twin-prime-number-from-a-range-determined-by-the-user-in-fortran – Ross Mar 21 '17 at 02:15
  • 3
    Possible duplicate of [How find a twin prime number from a range determined by the user in Fortran](http://stackoverflow.com/questions/42882840/how-find-a-twin-prime-number-from-a-range-determined-by-the-user-in-fortran) – Ross Mar 21 '17 at 02:16
  • I don't think they should be necessarily closed as duplicates. They can have different problems. But the OP should state what *"doesn't work"* means. Where he sees a problem. Which results he gets and why are they wrong. What error messages he gets. Two question for the same HW and both just with a code dump and *it doesn't work* are not useful. – Vladimir F Героям слава Mar 21 '17 at 07:39

2 Answers2

1

How you fix it is to run it through a "debugger" (either a real one or your head) to see what variables and effects are after each step.

However (though my Fortran is a little rusty), you appear to have chosen a particularly inefficient algorithm which selects many many prime-pairs (in nexted loops) and then evaluates whether their difference is two.

It will be a lot simpler with something like:

for num = lower to upper - 2:
    if num is prime and (num + 2) is prime:
        output num, num + 2
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • Apart from (3, 5) all twin primes are of the form (6n-1, 6n+1) which will cut down the number of possible pairs you need to test. – rossum Mar 21 '17 at 12:14
0

Not a complete answer, because this is homework, but one possible approach is to sieve the entire range for primes and then search it for pairs. Another (slower but possibly simpler and using less memory) is to do trial division on each odd number, and remember whether the last odd number was prime or not.

Davislor
  • 14,674
  • 2
  • 34
  • 49