4
$\begingroup$

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?

$\endgroup$

2 Answers 2

6
$\begingroup$

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

enter image description here

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]"}}]] 
$\endgroup$
2
  • $\begingroup$ Fab. I appreciate the help. $\endgroup$ Commented Jun 16, 2019 at 12:10
  • $\begingroup$ @Richard, my pleasure. Thank you for the accept. $\endgroup$ Commented Jun 16, 2019 at 12:11
4
$\begingroup$

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.

$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.