Parsing big integer as string

Hi there,

I’m trying to solve project euler #13 in julia. I have to give the first 10 digits of a humongous integer.
To obtain that integer, I have to read line by line a file with really big integers and summing them up. The solution will be the first ten digits of that integer.

I could sum them up but I’m getting troubles when parsing it. This part reads the file and calculate the result as a float:

using DoubleFloats
result = sum(parse.(Double64, readlines("my_file.txt")))

but the result is printed as “5.5373762303908766373020487468328705e+51”. If I try to parse it to a “BigInt” I get the following error:

ERROR: LoadError: MethodError: no method matching parse(::Type{BigInt}, ::Double64)

How can I get the first 10 digits of that big integer?

Thanks in advance

*“my_file.txt” has 100 big integers such as this one: 37107287533902102798797998220837590246510135740250

Each of these integers is in a new line without \n to separate them.

can you give an example of what code you are running to generate the error? I assume it is one of either
parse(Double64,result) or result = sum(parse.(BigInt,readlines("my_file.txt"))) or maybe something else but it is unclear what.

nbs = map(x->parse(BigInt,x),readlines(raw"C:\temp\data.txt"))
res = sum(nbs)
string(res)[1:10]
1 Like

or as a one liner I believe that
string(sum(parse.(BigInt,readlines("my_file.txt"))))[1:10]
should work…I think.

2 Likes

Sorry for not being more concrete. The code that generates the error is:

parse(Double64,result)

“result” isn’t a string so there is no need to parse it. (Parsing is basically for converting a string into some other datatype. Instead you need to convert result (which in your original example is a Double64) to a BigInt. This is performed by doing BigInt(result).

However as both @bernhard and I have shown there is no particular reason to use Double64, you can parse directly to BigInt as shown (I think, I was too lazy to create a demo file to try for sure but it should work).

2 Likes

Thx for the explanation. I’m learning lots of new things everyday :smiley: