メビウス関数


23

メビウス関数

メビウス関数は重要な数論関数です。

提出は正の整数nを受け入れ、で評価されたメビウス関数の値を返す必要がありますn

定義

メビウス関数μ(n)は次のように定義されます。

       |  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

nnの素因数分解の指数がすべて厳密に2よりも小さい場合、平方自由と呼ばれます。(または、2つの除算の累乗に対する素数はありませんn)。

テストケース

ここで、μの最初の50個の値を確認できます。

ウィキペディアのパブリックドメイン画像

メビウス関数は、OEISのシーケンス番号A008683です。

これらは最初の77の値です:

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

値が大きいほど、また、容易に確認することができるWolframalpha.comにまたはでOEISのB-ファイル MartinBüttner@により示唆されるように、。

回答:


15

Python 2、48バイト

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

以前の51バイトバージョン:

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

シーケンスをメビウス反転します1,0,0,0,0...

メビウス関数は任意のためという性質を持っているn>1の、メビウス機能n0ですからへの除数の総和、のためにn>1μ(n)和否定することによって計算されμ(k)、すべての適切な除数のためkのをn。の場合n=1、出力は1です。

コードは、床分割添加することにより、ベースケースを扱う1/n与える1ためn==1、および0そうでない場合に。

このチャレンジでの同様の構造に触発されたより良い再帰処理で3バイトを節約してくれたDennisに感謝します。


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

たとえば、番号10

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

そして結果 1になります。

オンラインでお試しください


-1バイト:(当時は組み込みであったÆFỊNPSかどうかはわかりませんが、今は問題ないはずです)。
エリックアウトゴルファー

10

Mathematica、9バイト

MoebiusMu

もちろん、Mathematicaには組み込み機能があります。(とにかく、おそらくゼリーにprobablyられます。)


7

CJam、18 15バイト

WrimFz~\1&+f/:*

CJamが因数分解組み込み関数で1を返すという事実はn = 1、物事を少し複雑にします。

オンラインで試す | テストスイート

@PeterTaylorに1&+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

の場合n > 1、変更された配列は単なる指数配列です。場合は、n平方、アレイは、分割後のすべて-1,2なる全て1S、です。そうでなく、nが素平方の除数を持っている場合、除算の後に0が存在し、0の積を与えます。

ためにn = 1修飾された配列で[1] + [1]なる、[-1 -1]1の生成物を与え、分割後。


代替16:

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

これは#、各[base exponent]配列で(find)を使用して1を探し、次にmapsを探します-1 -> 0, 0 -> 1, 1 -> -1


6

ルビー、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
}

「マジック」部分は、数値が偶数の場合は1、それ以外の場合は-1になります。方法は次のとおりです。

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
:
}
?   @ "}){/{=:
""({! "      ;
} )   :}}:={%"
* _}}){     ;
{      #}):{{
")`%#/{+

オンラインでお試しください!

簡単な説明

Pythonで使用されるアルゴリズムのポートを次に示します。

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)

長い説明

ラビリンスの通常の入門書:

  • Labyrinthはスタックベースの2次元であり、最初に認識された文字から実行が開始されます。メインスタックと補助スタックの2つのスタックがありますが、ほとんどのオペレーターはメインスタックでのみ動作します。
  • ラビリンスのすべてのブランチで、スタックの最上部がチェックされ、次に進むべき場所が決定されます。負は左に曲がり、0はまっすぐ進み、正は右に曲がります。

このプログラムの実行は左上から始まり1ます。

Outer preparation
=================

1        Pop 0 (stack is bottomless and filled with 0s) and push 0*10+1 = 1
:}       Duplicate and shift to auxiliary stack
?        Read int from input
         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

あなたが持っている必要があります あなたのシステムにインストールされて数字パッケージいる ...

編集:仕様を適切に読んだ方がはるかに簡単です[@AlexAに感謝します。]


これは、1から入力までの各整数に対して評価されたメビウス関数を返しますが、このチャレンジのタスクは、入力に対してメビウス関数を単純に評価することです。
アレックスA.

Mathematicaの答えに沿って、単純numbers::moebiusに16バイトでもできます。
アレックスA.

3

Pyth、16バイト

?nl{PQlPQZ^_1lPQ

オンラインでお試しください!

私の最初の実際のPythの答え。提案に感謝します!:)

説明

私の解決策は、その素因数に複数の数が含まれていない場合、数は平方なしであるという事実を使用しています。入力が平方なしの場合、メビウス関数は値-1 ^(素因数)を取ります。


?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^*

これは、言語/コンパイラの現在のリリース(10.1.0)を使用します。

オンラインでお試しください!

説明

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バイト、非競合

Dammit、これもバグであり、私の提出物が競合しないようにします。コード:

.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

CP-1252エンコーディングを使用


ISO 8859-1ではありません
...-ETHproductions

1
@ETHproductionsへっ?それでは、どのようなエンコーディングですか?このサイトから入手しました。
アドナン

拡張ASCIIと呼ばれると思います。
ETHproductions

@ETHproductionsありがとう、私は投稿を編集しました:)
アドナン

@ThomasKwaああ、私はそれを見つけました。それはCP-1252エンコーディング。
アドナン

2

Pyth、11

*{IPQ^_1lPQ

テストスイート

これは、素因数が平方自由である場合のブール値に-1、その数が持つ素因数の累乗を掛けます。

Iは、前の演算子(ここでは{)の不変性チェックで、unique-ify演算子です。



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

真剣に、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を0からifから3進数に変更(Kevin Cruijssenに感謝)
数に変更 -7バイト:forループのifステートメントを3進数に変更(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
ええ、それについてすみません。:)ゴルフへの1つの以上のバイトは、ところでですif(a%i<1)b=0;b=a%i<1?0:b;
ケビンクルーイッセン

2
実際には、それは簡単な改善を見落としています。b=-b;b=a%i<1?0:b;ゴルフへb=a%i<1?0:-b;
ピーターテイラー

1
上記の@PeterTaylorのゴルフを続けると、に変更if(a%i<1){a/=i;b=a%i<1?0:-b;}b=a%i<1?(a/=i)%i<1?0:-b:b;てさらに3バイト節約できます。
ケビンクルーイッセン



1

Microsoft Office Excel、英国版、196バイト

=IF(ROW()>=COLUMN(),IF(AND(ROW()=1,COLUMN()=1),1,IF(COLUMN()=1,
-SUM(INDIRECT(ADDRESS(ROW(),2)&":"&ADDRESS(ROW(),ROW()))),
IF(MOD(ROW(),COLUMN())=0,INDIRECT(ADDRESS(FLOOR(ROW()/COLUMN(),1),
1)),""))),"")

セルA1〜AX50に入力するExcelセル式。



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.

Nice solution =)(ただし、この言語は質問よりも若いと思いますか?)
flawr

@flawrどうやら答えはまじめに同じように機能し、実際に最初にオンラインになったのはいつか分からないので、安全のためにまじめに変更しました。
シャーロック

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;}

@PeterTaylorのおかげで-4バイト。

@Meerkatのポート。

オンラインでお試しください。

説明:

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

まず第一に-これは私の最初のコードのゴルフ投稿なので、ある程度規則を誤解するかもしれません。この投稿では最後のキャラクター;は省略できますが、それでも動作しますが、ES6仕様に従ってコードが有効かどうかはわかりません。とにかく、簡単な説明。

最初に、このアイデアについて少し説明します。を取りn、整数で割ってみますiます。割り切れる場合は、それを行い、i再度割り切れるかどうかを確認します。その場合は、を返す必要があり0ます。それ以外の場合は、別のを試すことができiます。クールなのは、すべての素因数を分割するために、毎回i=2それを増やして増やすだけ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

だから、それは私の提出です。


サイトへようこそ。私はjsを知りませんが、ここでは仕様だけを気にせず、実装のみを気にすることができます。したがって、削除;しても破損しない場合は、削除できる仕様は関係ありません。
小麦ウィザード

知っておきたい!その後削除します;)
vrugtehagel
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.