Welcome to Day 4 of the Perl 6 One-Liner Advent Calendar!
Today, we’ll look at the Problem 13 of Project Euler. Let me show a screenshot of it:
Indeed, it looks huge, and the task is to find the first ten digits of the sum of a hundred integers, each consisting of 50 digits.
Sounds like a task that may require some optimisation and simplification to get rid of everything which does not contribute to the first ten digits of the result. But not in Perl 6.
In Perl 6, you can simply add up the numbers and take the first ten digits of it:
<
37107287433902102798797998220837590246510135740250
# Other 98 numbers here
53503534526472524250874054075591789781264330331690
>.sum.substr(0, 10).say
Perl 6 is operating with arbitrary-long integers by default; you don’t need to include any modules or somehow else activate this behaviour. You can even calculate powers and get the result quickly enough:
$ perl6 -e'say 37107287433902102798797998220837590 ** 1000'
Another thing to notice is that we can transparently cast strings to numbers and vice versa. In our today’s program, the list of numbers is presented as a quoted list of strings within a pair of angle brackets.
On the list, you call the sum method, which works with numbers. After getting the sum, you treat it as a string again and extract the first ten characters of it. The whole code looks very natural and easy to read.
And with this mood, we’ll say ‘Goodbye’ till tomorrow!
The sum method takes la list so “combing” first would help.
37107287433902102798797998220837590246510135740250.comb.sum.substr(0, 10).say
Note: this may have changed, I run Rakudo version 2018.10 built on MoarVM version 2018.10 implementing Perl 6.c.
Bregs,
I think you misunderstood the problem. The huge list is not a single number but a list of 100 50-digit-long numbers.
I also missed the word quoting in your piece of code.
Going from array of IntStr , to Int , to Str
My bad
Bregs,