I want to make a program that finds twin prime numbers in a certain range, from n to m. Here it is what I have so far:
program twin
implicit none
integer i, count1, n, m, count2, j, k, pri1, pri2
count1 = 0
count2 = 0
read(5,*)n
read(5,*)m
do i = 1,m
do j = n,m
if (mod(j,i) ==0) then
count1 = count1 +1
else
count1 = count1
if(count1 ==0) then
pri1 = j
do k=j,m
if (mod(k,i)==0) then
count2 = count2 +1
else
count2 = count2
if(count2 ==0) then
pri2 = k
if (pri2-pri1 == 2) then
write(*,*)j,k
end if
end if
end if
end do
end if
end if
end do
end do
end program twin
I tried n = 4 and m = 8, expecting to get 5 and 7, the n = 70 and m = 74, wanting 71 and 73, but in both cases it doesn't return nothing, why is that?
I decided to rewrite your code using a function call. I always try to use functions and subroutines as much as possible when there is repeated code. In this case, the check to see if the integer was a prime is an obvious choice.
I also reduced the loops to only look at numbers between
m
andn
(I swapped them round because I'm funny like that) and once a prime has been found between that number andn
.There are several issues with the original code, the count variables are not reinitialized for each loop. Once this is fixed, there are problems when checking for a prime number. I have found it impossible, thus far, to maintain the original structure and return only genuine prime numbers. Problems arise from the
mod(j, i)
check. Wheni > j
, the code returnsj
as a prime. When alli
are not common factors ofj
, it returns a prime.