我只是想稍微熟悉Fortran(因为我可以)所以我写了这个小程序,它使用了Eratosthenes的Sieve来生成素数。这是程序:
program prime
implicit none
integer num_primes, at, found, i
logical is_prime
integer, allocatable, dimension(:) :: primes ! array that will hold the primes
print *, "How many primes would you like to find?"
read (*, *) num_primes
allocate (primes(num_primes))
primes(1) = 2
at = 2
found = 1
do
is_prime = .true. ! assume prime
do i = 1, found
if (modulo(at, primes(i)) == 0) then ! if divisible by any other element
is_prime = .false. ! in the array, then not prime.
at = at + 1
continue
end if
end do
found = found + 1
primes(found) = at
print *, at
at = at + 1
if (found == num_primes) then ! stop when all primes are found
exit
endif
end do
结束节目素数
运行它将显示错误是什么,例如,尝试找到10个素数将产生以下数字:3,5,7,11,13,16,17,19,23。显然16不是素数。可能有什么不对?
答案 0 :(得分:3)
这不是Eratosthenes的筛子,它不需要modulo
。
它是一种试验分割,但是当你找到一个除数时,你将at
递增1并开始测试你应该重新开始的下一个素数。
当你发现15可以除以3时,at
增加到16并且针对5,7,11进行测试,这当然不是16的除数,所以打印出16。
我不是FORTRAN程序员,但我认为你应该更换行
at = at + 1
continue
通过
exit
并执行
行found = found + 1
primes(found) = at
print *, at
仅当is_prime为真。
答案 1 :(得分:2)
这是通过实施Henrik建议的工作程序(然后我做了一些格式化更改):
program prime
implicit none
integer :: num_primes, at, found, i
logical :: is_prime
integer, allocatable, dimension(:) :: primes ! array that will hold the primes
print *, "How many primes would you like to find?"
read(*, *) num_primes
allocate(primes(num_primes))
primes(1) = 2
at = 2
found = 1
do
is_prime = .true. ! assume prime
do i = 1, found
if (modulo(at, primes(i)) == 0) then ! if divisible by any other element
is_prime = .false. ! in the array, then not prime.
exit
end if
end do
if (is_prime) then
found = found + 1
primes(found) = at
print *, at
end if
at = at + 1
if (found == num_primes) then ! stop when all primes are found
exit
end if
end do
end program prime
当你运行它时,你会得到:
How many primes would you like to find?
20
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
并且primes
数组将包含所有素数。那是你想要的吗?