Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raku list comprehension

I am in Windows 10 i7 4th gen laptop with 8 GB RAM.

I want to find out the sum of numbers from 1 to 1000000000 divisible by 5.

I am trying to run this code in the Raku REPL:

($_ if $_%5==0 for 1..1000000000).sum

The code is running for 45 mins and still there's no output. How can I overcome it?

What about and how to apply concurrency in such situation? I think above problem can be solved with concurrency or task parallelism!!

like image 952
Suman Khanal Avatar asked Feb 22 '17 12:02

Suman Khanal


1 Answers

How can I overcome it?

By choosing a better algorithm:

Let my \N = 1_000_000_000. You are interested in the value

[+] grep * %% 5, 1..N

which is the same as

[+] map * * 5, 1..N/5

which is in turn

5 * [+] 1..N/5

Rakudo is smart enough to sum a range in constant time and you'll get your result (almost) instantly.

like image 97
Christoph Avatar answered Oct 15 '22 07:10

Christoph