FORTRAN users, why this program ain't giving the correct answers?

Hey everyone,

this program tests a number and prints out: (true) if it's a prime number , (false) if it's not a prime number ..


INTEGER FUNCTION read_integer_value(prompt,minvalue,maxvalue)
IMPLICIT NONE
CHARACTER(LEN=*),INTENT(IN)::prompt
INTEGER,INTENT(IN)::minvalue,maxvalue
INTEGER::value,ioflag
WRITE(*,'(a)',ADVANCE='NO')prompt
READ(*,*,IOSTAT=ioflag)value
DO WHILE(ioflag/=0 .OR. value<minvalue .OR. value>maxvalue)
WRITE(*,'(a)',ADVANCE='NO')prompt
READ(*,*,IOSTAT=ioflag)value
END DO
read_integer_value=value
END FUNCTION read_integer_value

LOGICAL FUNCTION is_prime(n)
IMPLICIT NONE
INTEGER,INTENT(IN)::n
INTEGER::i,dv=0
IF(n==1) is_prime=.FALSE.
DO i=1,n
IF (mod(n,i)==0)then
dv=dv+1
end if
END DO
is_prime=dv==2
END FUNCTION is_prime

PROGRAM main_test
IMPLICIT NONE
INTEGER::num,i,read_integer_value
LOGICAL:: PRIME,is_prime
DO i=1,10
num=read_integer_value('Enter number: ',1,1000)
PRIME=is_prime(num)
WRITE(*,*) PRIME
END DO
END PROGRAM main_test

Note : dv variable is the number of the divisors.
the program works but it's not giving the right answers , so can anyone help?
thanks :)

Comments

  • I realize this is very late (OP is Feb 2012 and it's now nearly Dec 2012), but you are not correctly identifying prime numbers in the function is_prime. In fact, you are only identifying 1 as not-prime and nothing else about any number greater than it! Your function needs to be the following
    function is_prime(n) result(ans)
        implicit none
        integer,intent(in)::n
        logical::ans
        integer::i
    
        if(i <= 1)
           ans=.false.
        else if((n. == 2).or.(n == 3)) then
           ans=.true.
        else if(mod(n,2) == 0) then
           ans=.false.
        else
           i=3
           do
              if(i*i > n) then
                 ans=.true.; exit
              endif
              if(mod(n,i) == 0) then
                 ans=.false.;exit
              endif
              i=i+2
           enddo
        endif
    end function is_prime
    

    The code above works by identifying if the number is 0, 1, 2, 3, or an even number and giving the appropriate true/false. Then it starts identifying if the odd numbers (hence the i=3 --> i=i+2) are primes are not. There cannot be a prime factor above sqrt(n), so if we get i>sqrt(n) (in the code as i*i > n) we can safely get that it is indeed prime. But if n & i evenly divide (mod(n,i) == 0), then we know it is not prime.

    Note that this subroutine is extremely slow for large n! A seive (such as Atkin or Eratosthenes, both are on Wiki) is necessary when n is sufficiently large.
Sign In or Register to comment.