Search code examples
fortranprimes

Getting the prime numbers till 10000 in fortran?


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?


Solution

  • 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

    version with exit loop