Sunday, August 11, 2013

Return to Problem 3 with Fortran

During the original challenge, I used the J language on Problem 3 - J was a good language for problem 3, because the solution took 4 characters to write...but J is a good language for many Project Euler problems, so it was silly to use it so early. During the challenge, I didn't really get to use Fortran...it ended up finding an analytic solution, so the Fortran code I wrote was reduced to being nothing more than a multiplication. So, I decided to revisit problem 3, using Fortran this time. Now that I have gotten used to it to a certain extent, Fortran isn't the worst programming language (hey, its better than Whenever which I used yesterday), and my solution did indeed run more quickly than I expected it to (~6ms, even though I wasn't exactly doing the most efficient prime factoring in the world)

!Program 
program euler
implicit none
integer :: N, ans
N = 600851475143
ans = 0
call bigpfac(N, ans)
print *, ans
end program euler

subroutine isprime(x, output)
implicit none
integer :: i, x, output
output = 1

do i=2, int(sqrt(real(x)))
if (mod(x,i) == 0) then
    output = 0
exit
end if
end do
end subroutine isprime

subroutine bigpfac(x, output)
implicit none
integer :: i, x, output, p
output = 0
do i=3,x,2
    call isprime(i, p)
    if (x == 1) then
        exit
    end if
    if ((p == 1) .and. (mod(x,i) == 0)) then
        output = i
        x = x / i
    end if
end do
end subroutine bigpfac
 


No comments:

Post a Comment