Skip to content

Instantly share code, notes, and snippets.

@komasaru
Created April 20, 2017 05:04
Show Gist options
  • Save komasaru/11a2513001796fafd92de6f677732ec7 to your computer and use it in GitHub Desktop.
Save komasaru/11a2513001796fafd92de6f677732ec7 to your computer and use it in GitHub Desktop.
Fortran code to compute prime numbers.
!****************************************************
! 素数一覧
! : 入力値以下の素数を全て出力する
!
! date name version
! 2017.04.20 mk-mode.com 1.00 新規作成
!
! Copyright(C) 2017 mk-mode.com All Rights Reserved.
!****************************************************
!
program prime_numbers
implicit none
integer i, j, n
logical is_prime
print *, "自然数を入力してください N:"
read *, n
do i = 2, n
is_prime = .true.
do j = 2, int(sqrt(dble(i)))
if (mod(i,j) == 0) then
is_prime = .false. ! 割り切れるので素数ではない
exit
end if
end do
if (is_prime) print *, i ! もし素数ならば出力
end do
end program
@komasaru
Copy link
Author

If you ask me what you should do,
I'm very sorry, but I can only say that you should refer to this 'prime_numbers.f95' code.

@fbarbuto
Copy link

It could be a little better/more efficient/faster. The program doesn't have to check all numbers from 2 to n , only the odd ones.

                ...
                ! *** New lines block. ***
		If (n .GE. 2) Then 
			Write(*,*) 2                          ! Two is a prime.
		Else
			Return
		End If
                ! *** End of new lines block. ***

		Do i = 3, n, 2                                !<--- Change here.
			is_prime = .TRUE.
			Do j = 3, Int(Sqrt(Dble(i))), 2       !<--- Change here.
                        ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment