🎄 4/25. Working with big numbers in Perl 6

🎄 4/25. Working with big numbers in Raku

N. B. Perl 6 has been renamed to Raku. Click to read more.


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!

5 thoughts on “🎄 4/25. Working with big numbers in Perl 6”

  1. 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,

Leave a Reply

Your email address will not be published. Required fields are marked *

Retype the CAPTCHA code from the image
Change the CAPTCHA codeSpeak the CAPTCHA code