Reputation: 840
Im trying to print prime numbers till 10000. (display the first five for testing) This is my program
program primes
implicit none
integer :: array(1229)
integer :: i, ind
logical :: is_prime
ind = 1
do i = 2, 10000, 1
if (is_prime(i) .eqv. .true.) then
array(ind) = i
ind = ind + 1
end if
end do
print *, array(1)
print *, array(2)
print *, array(3)
print *, array(4)
print *, array(5)
end program primes
function is_prime(n) result(ispr)
implicit none
integer :: c, i
integer, intent(in) :: n
logical :: ispr
c = 0
do i = 2, n
if (mod(i,2) == 0) then
c = c + 1
end if
end do
ispr = (c == 0)
end function is_prime
I don't know why but this is the output
9175178
6417360
5374044
6750309
7536745
Why does this happen and how to correct?
Upvotes: 2
Views: 494
Reputation: 1251
While I am not familiar with modern Fortran, it looks to me as if function is_prime(n) result(ispr)
is not working.
In the do
loop in that function, you want a loop that tests thus:
n
divisible by 2?n
divisible by 3?n
divisible by 4?n
divisible by 5?and so on.
But, what it is actually doing is asking these:
and so on.
As a result, your counter will always have a non-zero value, and your function will always return false
.
But, that's not the only problem. From your results, it looks like your Fortran implementation does not automatically initialize variables. Suppose I have statements like the following:
integer :: b
print *,b
What will be the result?
Remember, the names of variables represent locations in the computer's memory. If a variable is not initialized, it's value will be what was in the memory location before your program started to run. This value will not be related to your program.
I have 2 suggestions to fix the 2nd problem:
Prior to do i = 2, 10000, 1
, have another loop that sets each value in array
.
Set a values of each array (i)
inside your do i = 2, 10000, 1
loop. One way to do this is to set one value when (is_prime(i) .eqv. .true.)
is true
and a different value when it is false
.
Upvotes: 2
Reputation: 4924
is_prime should be(n is the only divider of n besides 1 <=> c == 1)
function is_prime(n) result(ispr)
implicit none
integer :: c, i
integer, intent(in) :: n
logical :: ispr
c = 0
do i = 2, n
if (mod(n,i) == 0) then
c = c + 1
end if
end do
ispr = (c == 1)
end function is_prime
Could be optimezed by leaving the loop when c == 1 and i < n(after adding 1 to c)...
See on online fortran compiler
Upvotes: 4