23

# 莫比乌斯函数

### 定义

``````       |  1 if n is squarefree and has an even number of distinct prime factors
μ(n) = | -1 if n is squarefree and has an odd number of distinct prime factors
|  0 otherwise
``````

`n`如果n的质数分解的指数严格都小于2，则称为方自由。（或者：两个分割的幂都不是素数`n`）。

### 测试用例

``````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, -1, 0, 0, 0, 1, 0, -1, 0, 1, 0, 1, 1, -1, 0, -1, 1, 0, 0, 1, -1, -1, 0, 1, -1, -1, 0, -1, 1, 0, 0, 1
``````

15

## Python 2，48个字节

``m=lambda n,d=1:d%n and-m(d,n%d<1)+m(n,d+1)or 1/n``

``m=lambda n:1/n-sum(m(k)for k in range(1,n)if n%k<1)``

13

# 果冻，7个字节

``````ÆF>1’PS
``````

``````ÆF       # This computes the prime factorization as well as the exponent
>1     # Compares each element if it's greater than 1, resulting in 1's and 0's
’    # Decrement on each element
P   # Compute the product
S  # Compute the sum of the list
``````

``````ÆF       # [[2, 1], [5, 1]]
>1     # [[1, 0], [1, 0]]
’    # [[0, -1], [0, -1]]
P   # [0, 1]
S  # 1
``````

-1字节：（`ÆFỊNPS`不确定`Ị`当时是否是内置的，但现在应该可以了）。

10

## Mathematica，9个字节

``````MoebiusMu
``````

7

## CJam，18个 15字节

``````WrimFz~\1&+f/:*
``````

CJam在因式分解内置函数中返回1的事实`n = 1`使事情变得有些棘手。

## 说明

``````W                 Push -1
ri               Push input as int
mF             Factorise input into [base exponent] pairs
z~           Zip and unwrap pairs, leaving stack like [-1 bases exponents]
\1&        Setwise intersect bases with 1, giving [1] for 1 and [] otherwise
+       Append to exponent array
f/     Divide the previously pushed -1 by each element in the array
This gives -1 for 1s and 0 otherwise, since / is int division
:*   Take product
``````

``````rimF{1#2+3%(}%:*
``````

`#`在每个`[base exponent]`数组上使用（查找）查找1，然后映射`-1 -> 0, 0 -> 1, 1 -> -1`

6

## Ruby，65 + 7 = 72 62 + 7 = 69字节

``->x{((d=x.prime_division).all?{|_,n|n<2}?1:0)*(d.size%2*-2+1)}``

`-rprime`标志的+7个字节。

``````->x{
(
(d=x.prime_division)  # ex. input 20 results in [[2,2],[5,1]] here
.all?{|_,n|n<2}?      # are all factors' exponents under 2?
1:0                   # if so, result in a 1; otherwise, a 0
)
*                      # multiply that 1 or 0 by...
(d.size%2*-2+1)       # magic
}``````

``````Expression       Even  Odd
--------------------------
d.size%2         0     1
d.size%2*-2      0     -2
d.size%2*-2+1    1     -1``````

5

## Pyth，9个字节

``````^_{IPQlPQ
``````

``````^_{IPQlPQ    Implicit: Q=input
PQ       Prime factorization of Q
{I         Is invariant under uniquify.
{IPQ       1 if Q is squarefree; 0 otherwise.
_{IPQ       -1 if Q is squarefree; 0 otherwise.
^     lPQ    Exponentiation to length of PQ.
``````

5

## 迷宫，87字节

``````1
:
}
?   @ "}){/{=:
""({! "      ;
} )   :}}:={%"
* _}}){     ;
{      #}):{{
")`%#/{+
``````

### 简短说明

``````divisor = 1
mobius = 1
n = int(input())

while n != 1:
divisor += 1
count = 0

while n % divisor == 0:
n //= divisor
count += 1

mobius *= (count + 3)//(count + 1)%3*-1 + 1

print(mobius)``````

### 详细说明

• 迷宫是基于堆栈的和二维的，执行从第一个可识别的字符开始。有两个堆栈，一个主堆栈和一个辅助堆栈，但是大多数操作员仅在主堆栈上工作。
• 在迷宫的每个分支上，都要检查堆栈的顶部以确定下一步要去的地方。负数是左转，零是正数，正数是右转。

``````Outer preparation
=================

1        Pop 0 (stack is bottomless and filled with 0s) and push 0*10+1 = 1
:}       Duplicate and shift to auxiliary stack
Stack is now [div=1 n | mob=1]

Top of stack positive but can't turn right. Turn left into outer loop.

Begin outer loop
================
Inner preparation
-----------------

(        Decrement top of stack

If top was 1 (and is now zero), move forward and do...
------------------------------------------------------

{!       Print mob
@        Terminate

If top of stack was greater than 1, turn right and do...
--------------------------------------------------------

)        Increment n back to its previous value
_}       Push 0 and shift to aux
This will count the number of times n can be divided by div
}){      Increment div
Stack is now [div n | count mob]

Inner loop
----------

:}}      Dup n, shift both n's to aux
:=       Dup div and swap top of main with top of aux
{%       Shift div down and take mod
Stack is now [div n%div | n count mob]

If n%div == 0, move forward and do...
-----------------------------------

;        Pop n%div
:={/     Turn n into n/div
{)}      Increment count
(continue inner loop)

If n%div != 0, turn right (breaking out of inner loop) and do...
================================================================

;        Pop n%div
{{       Pull n and count from aux
:)}      Dup and increment count, giving (count+1), and shift to aux
#+       Add length of stack to count, giving (count+3)
{/       Calculate (count+3)/(count+1)
#%       Mod by length of stack, giving (count+3)/(count+1)%3
`        Multiply by -1
)        Increment, giving (count+3)/(count+1)%3*-1 + 1
This is 1 if count was 0, -1 if count was 1 and 0 if count > 1
{*}      Multiply mob by this number
(continue outer loop)
``````

4

# R 39 16字节

``````numbers::moebius
``````

Alex A.

Alex A.

3

# Pyth，16个字节

``````?nl{PQlPQZ^_1lPQ
``````

## 说明

``````
?n        if not equal
l{PQ      length of the list of the distinct input-Primefactors
lPQ       length of the list of primefactors including duplicates
Z         Input is not squarefree, so output Zero
^_1lPQ  if input is squarefree, output -1^(number of prime-factors)
``````

3

# MATL，15 17字节

``````tq?YftdAwn-1w^*
``````

### 说明

``````t         % implicit input. Duplicate that
q         % decrement by 1. Gives truthy (nonzero) if input exceeds 1
?         % if input exceeds 1, compute function. Otherwise leave 1 on the stack
Yf      % vector of prime factors. Results are sorted and possibly repeated
td      % duplicate and compute differences
A       % true if all differences are nonzero
w       % swap
n       % number of elements in vector of prime factors, "x"
-1w^    % -1^x: gives -1 if x odd, 1 if x even
*       % multiply by previously obtained true/false value, so non-square-free gives 0
% implicitly end "if"
% implicitly display stack contents
``````

3

# 05AB1E，8字节，非竞争

``````.p0K1›<P
``````

``````.p        # Get the prime factorization exponents
0K      # Remove all zeroes from the list
1›    # Compare each element if greater than 1
<   # Decrement on each element
P  # Take the product
``````

`›`不在ISO 8859-1中...
ETHproductions'Jan

1
@ETHproductions嘿？那是什么样的编码？我从这个网站上得到的。

ETHproductions 2016年

@ETHproductions谢谢，我已经编辑了帖子:)

2

# 珀斯，11岁

``````*{IPQ^_1lPQ
``````

`I`是对先前运算符的不变性检查，这里是`{`，这是唯一化运算符。

2

# 朱莉娅66字节

``n->(f=factor(n);any([values(f)...].>1)?0:length(keys(f))%2>0?-1:1)``

``````function µ(n::Int)
# Get the prime factorization of n as a Dict with keys as primes
# and values as exponents
f = factor(n)

# Return 0 for non-squarefree, otherwise check the length of the list
# of primes
any([values(f)...] .> 1) ? 0 : length(keys(f)) % 2 > 0 ? -1 : 1
end``````

2

# PARI / GP，7个字节

``moebius``

2

## 严重的是19 18字节

``````,w;`iX1=`Mπ)l1&τD*
``````

``````,w;`iXDY`Mπ)l1&τD*
,w;                push two copies of the full prime factorization of the input
(a list of [base, exponent] pairs)
`    `M         map the following function:
iX1=             flatten list, discard, equal to 1
(push 1 if exponent == 1 else 0)
π)       product of list, push to bottom of stack
1&     push 1 if the # of prime factors is even else 0
τD   double and decrement (transform [0,1] to [-1,1])
*  multiply
``````

2

# C＃（.NET Core），86 73 72 65字节

``a=>{int b=1,i=1;for(;++i<=a;)b=a%i<1?(a/=i)%i<1?0:-b:b;return b;}``

-13字节：简化的循环，添加了返回变量（感谢Kevin Cruijssen
-1字节：将设置b从if更改为三进制（感谢Kevin Cruijssen
-7字节：将if语句在for循环中更改为三进制（感谢Peter TaylorKevin Cruijssen

``````a => {
int b = 1, i = 1;           // initialize b and i to 1

for(; ++i <= a;)            // loop from 2 (first prime) to a
b = a % i < 1 ?                     // ternary: if a is divisible by i
((a /= i) % i < 1 ? 0 : -b) :   // if true: set b to 0 if a is divisible by i squared, otherwise flip sign of b
b;                              // if false: don't change b

return b;                   // return b (positive for even numbers of primes, negative for odd, zero for squares)
}``````

1
73个字节，我已更改`int b=1;for(int i=1;``int b=1,i=1;for(;`。删除`{}`了循环的- 括号。都更改`a%i==0``a%i<1`。更改`b*=-1;``b=-b;`。最后更改`return 0;``b=0;`

1

2

1

1

# GNU sed，89个字节

``````#!/bin/sed -rf
s/.*/factor &/e
s/.*://
/\b([0-9]+) \1\b/!{
s/[0-9]+//g
s/\$/1/
s/  //g
y/ /-/
}
s/ .*/0/
``````

1

# J，18个字节

``````[:*/3<:@|2+2<._&q:
``````

1

## Microsoft Office Excel，英语版，196字节

``````=IF(ROW()>=COLUMN(),IF(AND(ROW()=1,COLUMN()=1),1,IF(COLUMN()=1,
1)),""))),"")
``````

1

# 朱莉娅，35个字节

``````\(n,k=1)=k%n>0?n\-~k-k\0^(n%k):1÷n
``````

1

# 严重的是11个字节

``````;y;l0~ⁿ)π=*
``````

``````     Implicit input n.
;    Duplicate n.
y    Push a list of the distinct prime factors of n. Call it dpf.
;    Duplicate dpf.
l    Push len(dpf).
0~   Push -1.
ⁿ    Push (-1)**len(dpf).
)    Rotate (-1)**len(dpf) to BOS. Stack: dpf, n, (-1)**len(dpf)
π    Push product(dpf).
=    Check if product(dpf) == n.
This is only true if n is squarefree.
*    Multiply (n is squarefree) by (-1)**len(dpf).
Implicit return.
``````

@flawr显然，在“认真”中答案也同样有效，并且我不知道“实际上”何时首次上线，因此为了安全起见，我改为“认真”。
Sherlock16年

1

# Java 8，72 68 65字节

``n->{int r=1,i=1;for(;++i<=n;)r=n%i<1?(n/=i)%i<1?0:-r:r;return r;}``

-4个字节，感谢@PeterTaylor

@Meerkat 的.NET C＃答案的端口，我首先对其打了一点点，所以请确保对他投票！

``````n->{                 // Method with integer as both parameter and return-type
int r=1,           //  Result-integer, starting at 1
i=1;for(;++i<=n;)  //  Loop `i` in the range [1, n]:
r=n%i<1?         //   If `n` is divisible by `i`:
(n/=i)        //    Divide `n` by `i` first
%i<1?        //    And if `n` is still divisible by `i`:
0           //     Change `r` to 0
:            //    Else:
-r          //     Swap the sign of `r` (positive to negative or vice-versa)
:              //    Else:
r;            //     Leave `r` unchanged
return r;}         //  Return `r` as result``````

@PeterTaylor Smart，谢谢！然后使用可以再保存3个字节`r=n%i<1?(n/=i)%i<1?0:-r:r;`

0

## Javascript（ES6），48个字节

``````f=(n,i=1)=>n-1?n%++i?f(n,i):(n/=i)%i?-f(n,i):0:1
``````

``````f=(n,i=1)=>                                           We will increase i by one at the start of
the function body, so default is 1
n-1?                                       Check if n==1.
n%++i?                                 If i isn't, increase i by 1, check if n
is divisible by i
f(n,i):                          if it isn't, we check the next i
(n/=i)%i?                 if it is, divide n by i, and check for
divisibility by i again
-f(n,i):         if it not, then we flip the value to
account for the 1 and -1 depending on the
amount of factors
0:       if it's divisible by i twice, done.
1      if we're at 1, divided out all factors,
then we return 1. The line with
-f(n,i) will then take care of the sign
``````

vrugtehagel