Raku Books / Raku One-Liners / Working with Numbers
Working with big numbers
In this section, we’ll look at the Problem 13 of Project Euler. Let me show a part of it:
37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
91942213363574161572522430563301811072406154908250
23067588207539346171171980310421047513778063246676
89261670696623633820136378418383684178734361726757
28112879812849979408065481931592621691275889832738
44274228917432520321923589422876796487670272189318
47451445736001306439091167216856844588711603153276
70386486105843025439939619828917593665686757934951
62176457141856560629502157223196586755079324193331
64906352462741904929101432445813822663347944758178
92575867718337217661963751590579239728245598838407
58203565325359399008402633568948830189458628227828
80181199384826282014278194139940567587151170094390
35398664372827112653829987240784473053190104293586
86515506006295864861532075273371959191420517255829
71693888707715466499115593487603532921714970056938
54370070576826684624621495650076471787294438377604
53282654108756828443191190634694037855217779295145
36123272525000296071075082563815656710885258350721
45876576172410976447339110607218265236877223636045
17423706905851860660448207621209813287860733969412
81142660418086830619328460811191061556940512689692
. . .
72107838435069186155435662884062257473692284509516
20849603980134001723930671666823555245252804609722
53503534226472524250874054075591789781264330331690Indeed, the numbers look 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 Raku.
Here, 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).sayRaku 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:
$ raku -e'say 37107287433902102798797998220837590 ** 1000'Another thing to notice is that we can transparently cast strings to numbers and vice versa. In the current 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 it is easy to read.
Course navigation
← Generating random integers | Testing palindromic numbers →