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:
# Other 98 numbers here
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!