๐ŸŽ„ 4/25. Working with big numbers in Perl 6

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



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s