Friday, March 28, 2014

A single letter and bringing back an old friend - Problem 20 in E

There are a lot of languages with single letter names. To name just the ones used so far in this language challenge, C,D,J,K,R are all languages, and F# deserves an honorable mention. Even the letters that are not associated with languages too many people care about are associated with languages though, as I learned today with E. The hardest part of E was figuring out how to do anything without very much documentation to rely on, but once I figured out how to do things, there wasn't too much issue. The last time I solved problem 20 was way back in the 24-hour 20-problem hackathon that began all of this, and as it was towards the end of the hackathon, I threw a capable language at it, despite it being an easy problem. However, that capable language was Java, which, though I took a semester-long class taught in it, is not exactly my favorite language. However, using it in problem 20 simply because it had the BigInteger class was a bit silly. So, I have now recovered problem 20, and I did so without relying on anything like a BigInteger, instead explicitly storing the big number as an array of digits and doing some work by hand. So, problem 20 is solved, E is used, and Java is free. Solution runs in about 4.8 seconds on my machine, but the E interpreter has such a slow start up time that Hello World runs in about 4.1 seconds, so timing is pretty unreliable.
var d := [1]
def digits := d.diverge()


for x in 2..100 {
    var carry := 0
    for i in 0..(digits.size()-1) {
        var prod := (digits[i] * x) + carry
        digits[i] := prod % 10
        carry := prod // 10
    }
    while (carry > 0) {
        digits.push( carry % 10)
        carry := carry // 10
    }
}

var digisum := 0

for d in digits {
    digisum += d
}

println(digisum)


No comments:

Post a Comment