问题
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?
回答1:
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
and n
(I swapped them round because I'm funny like that) and once a prime has been found between that number and n
.
program twin
implicit none
integer :: m, n, i, j, prime1, prime2
read(*,*)m
read(*,*)n
do i = m, n
if (is_prime(i)) then
prime1 = i
do j = i, n
if (is_prime(j)) then
prime2 = j
if (prime2-prime1 == 2) then
write(*,*)i, j
end if
end if
end do
end if
end do
contains
function is_prime(num) result(output)
implicit none
integer, intent(in) :: num
logical :: output
integer :: i
integer :: count
count = 0
if (num > 1) then
do i = 2, num-1
if (mod(num, i) == 0) then
count = count + 1
end if
end do
else
count = count + 1
end if
if (count .eq. 0) then
output = .true.
else
output = .false.
end if
end function is_prime
end program twin
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. When i > j
, the code returns j
as a prime. When all i
are not common factors of j
, it returns a prime.
program twin
implicit none
integer i, count1, n, m, count2, j, k, pri1, pri2
count1 = 0
count2 = 0
pri1 = 0
pri2 = 0
read(5,*)n
read(5,*)m
do i = n, m
count1 = 0
do j = 2, i - 1
if (mod(i, j) == 0) then
count1 = count1 + 1
else
count1 = count1
end if
end do
if (count1 == 0) then
pri1 = i
do k = i, m
count2 = 0
do j = 2, k - 1
if (mod(k, j) == 0) then
count2 = count2 + 1
else
count2 = count2
end if
end do
if (count2 == 0) then
pri2 = k
if (pri2 - pri1 == 2) then
write(*,*) pri1, pri2
end if
end if
end do
end if
end do
end program twin
来源:https://stackoverflow.com/questions/42882840/how-find-a-twin-prime-number-from-a-range-determined-by-the-user-in-fortran