An positive integer greater than or equal to 2 is a prime number if the only divisor of this integer is 1 and itself.
Write a program that reads in an arbitrary integer and determines if it is a
prime number.
! --------------------------------------------------------------------
! Given an integer, this program determines if it is a prime number.
! This program first makes sure the input is 2. In this case, it is
! a prime number. Then, it checks to see the input is an even
! number. If the input is odd, then this program divides the input
! with 3, 5, 7, ....., until one of two conditions is met:
! (1) if one these odd number evenly divides the input, the
! input is not a prime number;
! (2) if the divisor is greater than the square toot of the
! input, the input is a prime.
! --------------------------------------------------------------------
PROGRAM Prime
IMPLICIT NONE
INTEGER :: Number ! the input number
INTEGER :: Divisor ! the running divisor
READ(*,*) Number ! read in the input
IF (Number < 2) THEN ! not a prime if < 2
WRITE(*,*) 'Illegal input'
ELSE IF (Number == 2) THEN ! is a prime if = 2
WRITE(*,*) Number, ' is a prime'
ELSE IF (MOD(Number,2) == 0) THEN ! not a prime if even
WRITE(*,*) Number, ' is NOT a prime'
ELSE ! we have an odd number here
Divisor = 3 ! divisor starts with 3
DO ! divide the input number
IF (Divisor*Divisor > Number .OR. MOD(Number, Divisor) == 0) EXIT
Divisor = Divisor + 2 ! increase to next odd
END DO
IF (Divisor*Divisor > Number) THEN ! which condition fails?
WRITE(*,*) Number, ' is a prime'
ELSE
WRITE(*,*) Number, ' is NOT a prime'
END IF
END IF
END PROGRAM Prime
Click here to download this program.
Illegal input
2 is a prime
3 is a prime
46 is NOT a prime
97 is a prime
9797 is NOT a prime
A better choice is the square root of Number? Why is this strange value? If Number is divisible by a, then we can write Number=a*b for some b. If a is less than or equal to b, then a must be smaller than or equal to the square root of Number.
Therefore, the upper limit of Divisor is the square root of Number. Stated in a slightly different way, it is "the square of Divisor is less than or equal to Number". This is better since it only uses integer arithmetic, while the one using square root involves REAL numbers.
Since Divisor can only be odd numbers, step-size is 2.
This loop continues until one of the two conditions holds. If Divisor*Divisor > Number holds, then all odd numbers that are greater than or equal to 3 and less than or equal to the square root of Number have been tried and none of them can evenly divide Number. Therefore, Number is a prime number.
If MOD(Number,Divisor) == 0 holds, Divisor divides Number and Number is not a prime.