メルテンス関数を計算する


18

正の整数nが与えられた場合、Mertens関数 Mn)の値を計算します。ここで、

メルテンス

そしてμkは)であるメビウス関数μkは)場合は1 = kが異なる素因数の偶数を有する場合、-1 kは異なる素因数の奇数であり、0素因数が明確でない場合。

  • これはので、入力整数n > 0 に対してメルテンス関数を計算する関数またはプログラムの最短コードを作成します。
  • これは、OEISシーケンスA002321です。

テストケース

n M(n)
1 1
2 0
3 -1
4 -1
5 -2
6 -1
7 -2
8 -2
9 -2
10 -1
117 -5
5525 5
7044 -25
8888 4
10000 -23


1ではなくTrueを返すことができますか?関連するメタディスカッション:数値が必要な場合にブール値を許可する必要がありますか?
デニス

@Dennisあなたの言語がTrueを1として解釈するかどうかは確かです。-
マイル

回答:


6

ゼリー、6 バイト

:Ḋ߀SC

オンラインでお試しください!または、より小さいテストケースを確認します。(しばらく時間がかかります)

バックグラウンド

これはプロパティを使用します

デビッド・W・ウィルソンの所有物

A002321、その次の再帰式につながります。

再帰式

使い方

:Ḋ߀SC  Main link. Argument: n

 Ḋ      Dequeue; yield [2, ..., n].
:       Perform the integer division of n by each k in [2, ..., n].
  ߀    Recursively call the main link on each result.
    S   Sum; add the results from the recursive calls.
     C  Complement; map the sum r to 1 - r.

11

Mathematica、22 20バイト

2バイトを節約してくれた@milesに感謝します。

Tr@*MoebiusMu@*Range

説明

Range

1からリストを生成して入力します。

MoebiusMu

MoebiusMu各番号の検索

Tr

結果を合計します。


2
Mathematicaにすべての機能が組み込まれているのは大好きですが、通常はゴルフ言語よりも長いです。= D
DJMcMayhem

5
mthmcaのもう1つの呼び出し、コマンド名長最適化バージョンのMathematica。
マイケルスターン

11

パイソン2、45の 37バイト

f=lambda n,k=2:n<k or f(n,k+1)-f(n/k)

Ideoneでテストします。

バックグラウンド

これはプロパティを使用します

デビッド・W・ウィルソンの所有物

A002321、その次の再帰式につながります。

再帰式

使い方

商を使用してMを計算するだけでなく、それらの画像の合計も計算します。これにより、次の簡単な実装よりも8バイト節約できます。

M=lambda n:1-sum(M(n/k)for k in range(2,n+1))

場合fは単一の引数と呼ばれるN、オプションの引数k個のデフォルト2

n = 1の場合、Trueがn<k生成され、fはこの値を返します。これが基本ケースです。

n> 1の場合、n<k最初にFalseを返し、次のコードorが実行されます。f(n/k)は、合計の1つの項を再帰的に計算し、これがの戻り値から減算されますf(n,k+1)。後者はkをインクリメントし、再帰的にfを呼び出すため、kの可能な値を反復処理します。いったんN <K + 1又はn = 1でf(n,k+1)戻ります1を再帰を終了します。


うわー、それはメビウスの実装よりもさらに短いです。codegolf.stackexchange.com/a/70024/34718
mbomb007

ずっと短い。:)今、とにかく。
デニス


7

Brachylog22 20バイト

yb:1a+
$p#dl:_1r^|,0

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

説明

yb                 The list [1, 2, …, Input]
  :1a              Apply predicate 1 (second line) to each element
     +             Sum the resulting list


    $p#d               All elements of the list of prime factors of the Input are distinct
        l:_1r^         Output = (-1)^(<length of the list of prime factors>)
|                  Or
    ,0                 Output = 0

5

ゼリー、9 バイト

RÆFỊNP€FS

オンラインでお試しください!または、すべてのテストケースを確認します

使い方

RÆFỊNP€FS  Main link. Argument: n

R          Range; yield [1, ..., n].
 ÆF        Factor; decompose each integer in that range into prime-exponent pairs.
   Ị       Insignificant; yield 1 for argument 1, 0 for all others.
    N      Negative; map n to -n.
           This maps primes to 0, exponent 1 to -1, and all other exponents to 0.
     P€    Reduce the columns of the resulting 2D arrays by multiplication.
           The product of the prime values will always be 0; the product of the
           exponent values is 0 if any exponent is greater than, 1 if there is an
           even number of them, -1 is there is an odd number of them.
       FS  Flatten and sum, computing the sum of µ(k) for k in [1, ..., n].


3

ゼリー、7 バイト

Ị*%ðþÆḊ

あまり効率的ではありません。決定要因は難しいです。

オンラインでお試しください!または、より小さいテストケースを確認します。(しばらく時間がかかります)

バックグラウンド

これは、A002321の式を使用します

M(n)はブール行列A n×nの行列式です。ここでj = 1またはi |の場合、ai、j1ですj、それ以外の場合は0

使い方

Ị*%ðþÆḊ  Main link. Argument: n

   ð     Combine the preceding atoms into a chain (unknown arity).
         Begin a new, dyadic chain with arguments a and b.
Ị        Insignificant; return 1 iff a = 1.
  %      Compute a % b.
 *       Compute (a == 1) ** (a % b).
         This yields 1 if a = 1, or if a ≠ 1 and a % b = 0; otherwise, it yields 0.
    þ    Table; construct the matrix A by calling the defined chain for every pair
         of integers in [1, ..., n].
     ÆḊ  Compute the determinant of the resulting matrix.

3

PHP、113バイト

for(;$i=$argv[1]--;){for($n=$j=1;$j++<$i;)if(!($i%$j)){$i/=$j;$n++;if(!($i%$j))continue 2;}$a+=$n%2?1:-1;}echo$a;

私の知る限り、phpには素数機能のようなものがないため、これはちょっとした痛みです。おそらくもっとうまくやることができるでしょう。

次のように使用します:

 php -r "for(;$i=$argv[1]--;){for($n=$j=1;$j++<$i;)if(!($i%$j)){$i/=$j;$n++;if(!($i%$j))continue 2;}$a+=$n%2?1:-1;}echo$a;" 10000

2

ラケット103バイト

(λ(N)(for/sum((n(range 1 N)))(define c(length(factorize n)))(cond[(= 0 c)0][(even? c)1][(odd? c)-1])))

ゴルフをしていない:

(define f
  (λ(N)
    (for/sum ((n (range 1 N)))
      (define c (length (factorize n)))
      (cond
        [(= 0 c) 0]
        [(even? c) 1]
        [(odd? c) -1]))))

2

CJam(20バイト)

qiM{_,:)(@@f/{j-}/}j

オンラインデモ

OEISの式を使用します

sum(k = 1..n, a([n/k])) = 1。-デビッドW.ウィルソン、2012年2月27日

およびCJamのメモ演算子j

解剖

qi       e# Read stdin as an integer
M{       e# Memoise with no base cases
         e#   Memoised function: stack contains n
  _,:)(  e#   Basic manipulations to give n [2 .. n] 1
  @@f/   e#   More basic manipulations to give 1 [n/2 ... n/n]
  {j-}/  e#   For each element of the array, make a memoised recursive call and subtract
}j

2

JavaScript(ES6)、50バイト

n=>[1,...Array(n-1)].reduce((r,_,i)=>r-f(n/++i|0))

@DennisのPython回答のポート。


2

ジュリア、26 25バイト

!n=1-sum(map(!,n÷(2:n)))

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

バックグラウンド

これはプロパティを使用します

デビッド・W・ウィルソンの所有物

A002321、その次の再帰式につながります。

再帰式

使い方

単項演算子を再定義します私たちの目的のために。

n÷(2:n)再定義されたすべての必要な商を計算しますそれらの上にマッピングされ、最後にすべての再帰呼び出しの合計が1から減算されます。

残念ながら、

!n=1-sum(!,n÷(2:n))

二項は空のコレクションで停止するため、機能しません。

!n=n<2||1-sum(!,n÷(2:n))

これを修正しますが、バイトを保存せず、入力1に対してTrueを返します。


2

C、51 50 47バイト

f(n,t,u){for(t=u=1;n/++u;t-=f(n/u));return t;}

編集:-3バイトの@Dennisに感謝!


1

Scala、53バイト

def?(n:Int,k:Int=2):Int=if(n<k)1 else?(n,k+1)- ?(n/k)

デニスのピチン回答のポート。

メソッドを呼び出しました?。これは、文字にこだわらないトークンです。



1

実際には、18 17 16バイト

ゴルフの提案を歓迎します。オンラインでお試しください!

R`;y;l0~ⁿ)π=*`MΣ

アンゴルフ

         Implicit input n.
R        Push the range [1..n].
`...`M   Map the following function over the range. Variable k.
  ;        Duplicate k.
  y        Push the distinct prime factors of k. Call it dpf.
  ;        Duplicate dpf.
  l        Push len(dpf).
  0~       Push -1.
  ⁿ        Push (-1)**len(dpf).
  )        Move (-1)**len(dpf) to BOS. Stack: dpf, k, (-1)**len(dpf)
  π        Push product(dpf).
  =        Check if this product is equal to k.
            If so, then k is squarefree.
  *        Multiply (k is squarefree) * (-1)**(length).
            If k is NOT squarefree, then 0.
            Else if length is odd, then -1.
            Else if length is even, then 1.
           This function is equivalent to the Möbius function.
Σ        Sum the results of the map.
         Implicit return.


0

J、19バイト

1#.1*/@:-@~:@q:@+i.

n範囲にわたるメビウス関数の合計を使用して、メルテンス関数を計算します[1, n]

使用法

   f =: 1#.1*/@:-@~:@q:@+i.
   (,.f"0) 1 2 3 4 5 6 7 8 9 10 117 5525 7044 8888 10000
    1   1
    2   0
    3  _1
    4  _1
    5  _2
    6  _1
    7  _2
    8  _2
    9  _2
   10  _1
  117  _5
 5525   5
 7044 _25
 8888   4
10000 _23

説明

1#.1*/@:-@~:@q:@+i.  Input: integer n
                 i.  Range [0, 1, ..., n-1]
   1            +    Add 1 to each
             q:@     Get the prime factors of each
          ~:@        Sieve mask of each, 1s at the first occurrence
                     of a value and 0 elsewhere
        -@           Negate
    */@:             Reduce each using multiplication to get the product
1#.                  Convert that to decimal from a list of base-1 digits
                     Equivalent to getting the sum
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.