Table the LCM of an increasing list

I want to create a table showing LCM[1,2], LCM[1,2,3], LCM[1,2,3,4], ..., LCM[1,2,3,...,m]. I figure I should be able to use Range to do this, but I can't quite figure out how. My attempt so far:

Module[{m = 10},
table = Table[Range[n], {n, 1, m}];
TableForm[
Table[{n, LCM[table[[n]]]}, {n, 1, m}],
TableHeadings -> {None, {"n", "LCM[1\[Rule]n]"}}]]


This doesn't work. I suspect it's something to do with how the list table is 'wrapped' in parentheses {{...},{...},...,{...}} but I'm not really sure.

How do I do it?

2 Answers

Update: Much faster alternative using FoldList:

ClearAll[lCM]
lCM = FoldList[LCM] @* Range

r3 = lCM[10^4]; // AbsoluteTiming


{0.023673, Null}

versus lcm from Carl's answer:

Clear[lcm];
lcm[1] = 1;
lcm[n_] := lcm[n] = LCM[n, lcm[n - 1]]

r2 = lcm /@ Range[10^4]; // AbsoluteTiming


{0.060979, Null}

r3 == r2


True

Original answer:

Use LCM @@ table[[n]] instead of LCM[table[[n]]] to get

An alternative way using a single Table:

Module[{m = 10},
TableForm[
Table[{n, LCM @@ Range[n]}, {n, 1, m}],
TableHeadings -> {None, {"n", "LCM[1\[Rule]n]"}}]]

• Fab. I appreciate the help. – Richard Burke-Ward Jun 16 '19 at 12:10
• @Richard, my pleasure. Thank you for the accept. – kglr Jun 16 '19 at 12:11

If you're interested in doing this for large values of m, then it would be much faster to use a memoized version:

lcm[1] = 1;
lcm[n_] := lcm[n] = LCM[n, lcm[n-1]]


An example showing it works:

lcm /@ Range[10]


{1, 2, 6, 12, 60, 60, 420, 840, 2520, 2520}

reproducing kglr's answer. Now, for a much larger value of m:

r1 = Table[LCM @@ Range[n], {n, 1, 10^4}]; //AbsoluteTiming


{35.862, Null}

Using lcm instead:

Clear[lcm];
lcm[1]=1;
lcm[n_]:=lcm[n]=LCM[n,lcm[n-1]]
r2 = lcm /@ Range[10^4]; //AbsoluteTiming


{0.04681, Null}

Check:

r1 === r2


True

So, about 1000 times faster than the non-memoized version.