Möbius function: Difference between revisions

Content added Content deleted
(Added Easylang)
(→‎J: simplify)
Line 1,245: Line 1,245:
=={{header|J}}==
=={{header|J}}==
Implementation:
Implementation:
<syntaxhighlight lang="j">mu=: (2&(*./@:>) * _1 ^ 2 | +/)@q:~&_</syntaxhighlight>
<syntaxhighlight lang="j">mu=: */@:-@~:@q:</syntaxhighlight>


Explanation: <code>_ q: n</code> gives the list of exponents of prime factors of n. (This is an empty list for the number 1, is 2 0 2 for the number 100 and is 3 1 1 for the number 120.)
Explanation: <code>q: n</code> gives the list of prime factors of n. (This is an empty list for the number 1, is <code>2 2 5 5</code> for the number 100, and is <code>2 2 2 3 5</code> for the number 120.)


In this context <code>+/</code> is the sum of that list, <code>2 | +/</code> is 1 if the sum is odd and 0 if the sum is even. <code>_1 ^ 0</code> is 1 and <code>_1 ^ 1</code> is -1. And, <code>2 *./@:&gt;</code> returns zero, if any exponent is at least 2 in magnitude.
In this context <code>~:</code> replaces each prime factor either by 1, if it is its first occurrence, or by 0, if it is a repetition (e.g. <code>2 2 5 5</code> <code>1 0 1 0</code>). Then, <code>-</code> simply negates this list (e.g. <code>1 0 1 0</code> <code>_1 0 _1 0</code>), and finally <code>*/</code> multiplies all list elements to get the desired result.


Task example:
Task example:
<syntaxhighlight lang="j"> mu 1+i.10 20
<syntaxhighlight lang="j"> mu >: i. 10 20
1 _1 _1 0 _1 1 _1 0 0 1 _1 0 _1 1 1 0 _1 0 _1 0
1 _1 _1 0 _1 1 _1 0 0 1 _1 0 _1 1 1 0 _1 0 _1 0
1 1 _1 0 0 1 0 0 _1 _1 _1 0 1 1 1 0 _1 1 1 0
1 1 _1 0 0 1 0 0 _1 _1 _1 0 1 1 1 0 _1 1 1 0