Cartesian LCM of two arrays Given two nonempty arrays of natural numbers \$a\$ and \$b\$, return the shortest nonempty array of pairs of natural numbers \$q\$ such that the sequence of first elements of \$q\$ consists of a whole number of repeated copies of \$a\$, and the sequence of second elements of \$q\$ consists of a whole number of repeated copies of \$b\$.

When \$a\$ and \$b\$ have the same length, this acts like a zip, but when the lengths of \$a\$ and \$b\$ are coprime, this acts like a Cartesian product.

You can use any reasonable input and output format for arrays (pointers, lists, space-separated strings, strings of char codes, etc.)

This is code-golf, so the shortest valid answer (measured in bytes) wins.

Test Cases

[1],          [2]       -&gt; [(1, 2)]
[1, 2],       [3]       -&gt; [(1, 3), (2, 3)]
[1, 2],       [3, 4]    -&gt; [(1, 3), (2, 4)]
[1, 2, 3, 4], [5, 6]    -&gt; [(1, 5), (2, 6), (3, 5), (4, 6)]
[5, 5, 5],    [5, 5, 5] -&gt; [(5, 5), (5, 5), (5, 5)]
[5, 5],       [5, 5, 5] -&gt; [(5, 5), (5, 5), (5, 5), (5, 5), (5, 5), (5, 5)]
[1, 2, 3, 4], [1, 2, 3, 4, 5, 6] -&gt;
    [(1, 1), (2, 2), (3, 3), (4, 4),
     (1, 5), (2, 6), (3, 1), (4, 2),
     (1, 3), (2, 4), (3, 5), (4, 6)]
J, 14 13 bytes

,./@($&amp;&gt;~*./)


Try it online!

-1 byte thanks to Bubbler

This answer takes the two lists as its left arg, and the two list lengths as its right arg.


($&amp;&gt;~*./) is a dyadic hook which applies gcd between the two right arg lengths *./ and the reshapes the two left arg lists $ to that length after opening them &amp;&gt;.  At this point they'll be the same length so boxing is no longer needed.
[:,./ so now we can just zip them ,.




original answer taking the lists directly

J, 17 16 bytes

(*.&amp;#$[),.*.&amp;#$]


Try it online!


*.&amp;# is the gcd *. after taking length # of both args


It turns out to be shorter to repeat this phrase than to remain DRY.


,. is zip and and $ is shape.  So we shape the left arg [ by the gcd of the list lengths, do the same to the right arg ], and zip them.