I found some rather non-Fortranic Fortran code on a blog, and after correcting it, thought it'd be a good example highlighting some of the perks of Fortran. I'm somewhat of a Fortran evangelist, so I like showing this stuff off. Here's the original code, cleaned up somewhat:

Code:

program primes
implicit none
integer, parameter :: max = 10000000
integer :: i, j, k, product(max), imax, jmax, numprime
do k = 1, 100
do i = 1, max
product(i) = 0
end do
numprime = 0
imax = floor(sqrt(real(max)))
do i = 2, imax
if (product(i) == 0) then
jmax = max/i
do j = 2, jmax
product(i*j) = 1
end do
end if
end do
do i = 2, max
if (product(i) == 0) then
numprime = numprime + 1
end if
end do
print *, 'Number of primes = ', numprime
end do
end program primes

And here would be a more preferred/optimal form:

Code:

program primes
implicit none
integer, parameter :: pmax = 10000000
integer :: i, k, imax
logical :: prod(pmax)
do k = 1, 100
prod(:) = .TRUE.
imax = floor(sqrt(real(pmax)))
do i = 2, imax
if (prod(i)) then
prod(2*i:pmax:i) = .FALSE.
end if
end do
print *, 'Number of primes = ', count(prod)-1
end do
end program primes

Changes:

- product and max are built-in function names, changed names

- can do a scalar assignment to an entire array

- can do a masked assignment to an array

- used the built-in function count appropriately