Tuesday, September 24, 2013

Problem 46 - Julia

I haven't solved a problem in a esoteric language too recently - rest assured, I am sure I will move back to esolangs soon, INTERCAL beckons. For now, however, there are still some entirely reasonable languages left for me to take advantage of. Most recently, I have used Julia - a language apparently designed like MATLAB and R with mathematical computation in mind, and like so many other languages I have used recently (especially with the stark contrast from things like Whitespace not too long ago), it was a very easy language to pick up and use for something not too bad like this. This problem involved Goldbach's "other" conjecture which conjectured that every odd composite was the sum of a prime and two times a square; this program disproves that conjecture in a handful of seconds.
function isPrime(x)
    if x < 2 || x % 2 == 0
        return x == 2
    end
    i = 3
    while i * i <= x
        if x % i == 0
            return false
        end
        i += 1
    end
    return true
end

primes = [2]
for i = 3:10000
    if isPrime(i)
        primes = [primes..., i]
    end
end

squares = [0]
for i = 1:1000
    squares = [squares..., i * i]
end

x = 7
while true
    gotans = false
    for p in primes
        done = false
        if p > x
            println(x)
            gotans = true
            break
        end
        for s in squares
            if x == p + 2*s
                done = true
                break
            end
            if p + 2*s > x
                break
            end
        end
        if done
            break
        end
    end
    if gotans
        break
    end
    x += 2
end

No comments:

Post a Comment