Solving Twin Primes with a Sieve Algorithm in Fortran

Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
4 replies · 4K views
ƒ(x) → ∞
Messages
24
Reaction score
0

Homework Statement



I have been trying to come up with a program to calculate twin primes using a sieve algorithm in Fortran. So far I have been successful in creating one that finds primes, but I am having difficulty finding one that finds prime twins. If I knew how to do this I could find prime quadruplets!

Homework Equations



-

The Attempt at a Solution



My sieve program is running perfectly, however having run the twin primes program through debugger was not as successful. It is finding what appear to be random numbers. Can anybody help?

My intial idea was to find prime numbers that differ by two.

program prime twins
implicit none
integer*1 s(100000)
integer i, j, n

n=0

do i=1, 100000
s(i) = 1
enddo

do i=2, 100000
if (s(i).eq.1) then
do j=2, (100000/i)
s(i*j)=0
enddo
endif
enddo

do i=2, 100000
if (s(i).eq.s(i+2).eq.1) then
n=n+1
write(*,*,*) n,i,i+2
endif
endo

end
 
Last edited:
Physics news on Phys.org
Added my solution.
 
You might be having problems in your last DO loop, in your IF statement.
ƒ(x) → ∞ said:
Code:
do i=2, 100000
  if (s(i).eq.s(i+2).eq.1) then
    n=n+1
    write(*,*,*) n,i,i+2 
  endif
enddo

I'm not sure how s(i) .EQ. s(i + 2) .EQ. 1 will actually evaluate. It would be clearer (and safer) to do this:
Code:
if ((s(i) .EQ. 1) .AND. (s(i + 2) .EQ. 1)) then

Also, there's no need to check each element of your array, since none of the elements with even indexes (except 2) are primes. So you can save a little processing time by starting at index 3 and skipping the even indexes.
Code:
DO i = 3, 100000, 2

Other things
You misspelled ENDDO in the final DO loop.
Your WRITE statement is incorrect. The asterisks are not placeholders for the expressions to be printed.
 
Thanks Mark for the help, some of the errors seem stupid now, but I wouldn't have found them without your help.