Wednesday, April 2, 2014

Problem 16 in (free)BASIC

Well, it was inevitable that I would have to use BASIC at some point. However, BASIC has far too many dialects. After some issues with getting it to run on my computer because of needing 32-bit versions of a lot of libraries, I decided to solve problem 16 in freeBASIC. I solved this problem to free up Frink for problem 80, as I think it will make that problem very tractable using its ability to use very large integers (indeed, that capability was why I used it on problem 16 in the first place, but I put in a little more work and managed digits by hand to solve it in BASIC). Didn't have too many issues with the language, other than having to discover that \ is integer division, while / will do float division and then round UP to the nearest integer. BASIC does indeed run quickly: solution runs in 34ms on my machine.
Dim digits(1000) As Integer
Dim numdigits As Integer
Dim i As Integer
Dim carry As Integer
Dim j As Integer
Dim prod As Integer
Dim ans As Integer

i = 0
numdigits = 1
digits(0) = 2
WHILE i < 999
    carry = 0
    j = 0
    WHILE j < numdigits
        prod = (digits(j) * 2) + carry
        digits(j) = prod Mod 10
        carry = prod \ 10
        j = j + 1
    WEND
    
    WHILE carry > 0
        digits(numdigits) = carry Mod 10
        numdigits = numdigits + 1
        carry = carry \ 10
    WEND
    i = i + 1
WEND

i = 0
ans = 0
WHILE i < numdigits
    ans = ans + digits(i)
    i = i + 1
WEND

print ans

No comments:

Post a Comment