# Thread: Good example of some of the perks of Fortran

1. ## Good example of some of the perks of Fortran

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

2. O_o

Languages with such "list comprehension" are very nice.

So, it has been a while for me and FORTRAN...

Code:
`prod(2*i:pmax:i) = .FALSE.`
That is saying "Recursively invalidate elements by assigning all elements from same elements within the next sparse array."?
[/Edit]

Soma

3. FWIW, the release of F77 coincided with the release of the original Star Wars. And now, the next revision is set to come out with the next episode.

4. FWIW, the release of F77 coincided with the release of the original Star Wars. And now, the next revision is set to come out with the next episode.
O_o

That explains the sinister leitmotif which followed one of my teachers: an "old hat" FORTRAN programmer.

Soma

5. That is saying "Recursively invalidate elements by assigning all elements from same elements within the next sparse array."?
O_o

Colleague answered my question: the selection happens "LHS" while the assignment--"RHS"--is handled iteratively "over" the scalar value.

So, I misunderstood the code a bit.

Soma

6. It basically is the equivalent of:

Code:
```for (j = 2*i; j < max; j += i)
prod(j) = false;```
but as far as Fortran goes, the whole idea with getting rid of as many DO loops as possible (in addition to making code smaller/neater), is to let the compiler know what can be vectorized.