首页 > 解决方案 > Fortran。使用检查素数的函数进行

问题描述

我最近在学习 Fortran,并试图制作一个程序来检查素数。该函数工作正常,没有任何循环。当给定数是素数时,它可以给出 1,否则为 0。但是,在 do while 循环中使用时不能正常工作。在 2 ~ 10 的范围内,它应该给出 1(对于 2)、1(对于 2)、0(对于 4)、1(对于 5)、0(对于 6)等。但是,它一直显示只有 0。我对编程很陌生,所以我不确定我错过了什么。我知道有很多与素数相关的答案,但我没有看到任何这样的问题。

**检查素数的功能**

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

** 结果 **

 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

标签: fortran

解决方案


对于 Fortran 新手来说,您有一个经典问题。itemp0暗示SAVE属性的初始化。当您isPrime第一次调用时,值被设置为 1 和 0。在下一次调用时,i和的值temp0被设置为它们isPrime上次执行时的先前值。归属程序解决了这个问题。

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

推荐阅读