0

I'm recently studying Fortran, and trying to make a program to check the prime number. The function works fine without any loop. It can give 1 when the given number is a prime number and 0 otherwise. However, it doesn't work properly when it is used in do while loop. In the range of 2 ~ 10, it is supposed to give 1 (for 2), 1(for 2), 0(for 4), 1(for 5), 0(for 6), etc. But, it keeps showing only 0. I'm pretty new to programming, so I'm not sure what I'm missing. I know there are many answers related to prime numbers, but I don't see any issue like this.

** Function checking prime numbers **

module prime_function

contains
integer function isPrime(inp_num)
    implicit none
    integer :: inp_num
    integer :: i = 1
    integer :: temp1 = 0
    
    do while (i < inp_num)
        i = i + 1
        if(mod(inp_num, i) == 0) then
            exit
        end if
    end do

    if(inp_num == i) then
        temp1 = 1
    else
        temp1 = 0
    end if
    isPrime = temp1
end function
end module

program fortran_q

use prime_function

implicit none
integer :: ii, a

a = isPrime(10)
print *, "10 is prime number, so the return : ", a

a = isPrime(11)
print *, "11 is prime number, so the return : ", a

ii = 1
do while (ii < 10)
    ii = ii + 1
    
    print *, isPrime(ii)
    
end do

end program

** Results **

 10 is prime number, so the return :            0
 11 is prime number, so the return :            1
 
 0
 0
 0
 0
 0
 0
 0
 0
 0

1 Answers1

0

You have a classic issue for people new to Fortran. The initialization of i and temp0 implies the SAVE attribute. When you call isPrime for the first time the values are set to 1 and 0. On the next invocation, the values of i and temp0 are set to whatever their previous values were when isPrime was last executed. The belong program fixes the issue.

module prime_function

  implicit none
  private
  public isprime

  contains

     function isPrime(inp_num) result(res)
        integer res
        integer, intent(in) :: inp_num
        integer i, temp1
        i = 1
        temp1 = 0
        do while (i < inp_num)
           i = i + 1
           if (mod(inp_num, i) == 0) exit
        end do
        res = 0
        if (inp_num == i) res = 1
     end function
end module

program fortran_q

  use prime_function

  implicit none
  integer :: ii, a

  a = isPrime(10)
  print *, "10 is prime number, so the return : ", a

  a = isPrime(11)
  print *, "11 is prime number, so the return : ", a

  ii = 1
  do while (ii < 10)
     ii = ii + 1
     print *, isPrime(ii)
  end do

end program
evets
  • 996
  • 1
  • 5
  • 6