Table the LCM of an increasing list
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]"}}]]
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.