Weekly Challenge #082 Task #1 :: (Raku)

jeongoon

Myoungjin Jeon

Posted on October 15, 2020

Weekly Challenge #082 Task #1 :: (Raku)

TASK #1 › Common Factors

Submitted by: Niels van Dijke

You are given 2 positive numbers $M and $N.

Write a script to list all common factors of the given numbers.
Example 1:

Input:
    $M = 12
    $N = 18

Output:
    (1, 2, 3, 6)

Explanation:
    Factors of 12: 1, 2, 3, 4, 6
    Factors of 18: 1, 2, 3, 6, 9
Enter fullscreen mode Exit fullscreen mode
Example 2:

Input:
    $M = 18
    $N = 23

Output:
    (1)

Explanation:
    Factors of 18: 1, 2, 3, 6, 9
    Factors of 23: 1
Enter fullscreen mode Exit fullscreen mode

It was really easy than I think it should be... quite opposite to Task #2 which I think easier.

If we are given N = 1000, We can get a series of divisors like below

> [ 1 .. 1000 ].grep({ 1000 %% $_ })
(1 2 4 5 8 10 20 25 40 50 100 125 200 250 500 1000)
Enter fullscreen mode Exit fullscreen mode

we can use for loop, or "gather and take" if you want.

if we are done with finding both divisors we can create a
set which contains intersection by

> [ 1 .. 12 ].grep({ 12 %% $_ }) (&) [ 1..18 ].grep({ 18 %% $_ })
Set(1 2 3 6)
Enter fullscreen mode Exit fullscreen mode

and only grab the values

([ 1 .. 12 ].grep({ 12 %% $_ }) (&) [ 1..18 ].grep({ 18 %% $_ })).keys.sort
(1 2 3 6)
Enter fullscreen mode Exit fullscreen mode

infix (&), infix ∩
I used "∩" infix during the Challenge #076 Task #2 as you can see in this code.
I wrote something like this perl code in Raku. but couldn't see big difference or slightly faster when using "Set".😅 so I thought "why should I use my own code if raku gives me faster one?", and changed it into simple line. quite convenient operators!!

gcd Infix

But we have gcd in Raku, so we don't have to make both divisors.

with [gcd] (12,18) { [ 1..$_ ].grep(-> \k { $_ %% k }) }
(1 2 3 6)
Enter fullscreen mode Exit fullscreen mode

Final Code

sub MAIN ( *@n where { @n.elems == 2 and @n.all ~~ Int and @n.all > 0 } ) {
    with [gcd] @n {
        say( [1.. $_].grep(-> \k {$_ %% k}));
    }
}
Enter fullscreen mode Exit fullscreen mode

If we are still unsure, we can still use "any"

sub MAIN ( *@n where { @n.elems == 2 and @n.all ~~ Int and @n.all > 0 } ) {
    say( [1.. @n.min].grep({any(@n)%%$_}) );
}
Enter fullscreen mode Exit fullscreen mode

Thank you for reading ~!

💖 💪 🙅 🚩
jeongoon
Myoungjin Jeon

Posted on October 15, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related