素数検定式


30

あなたの目標は、特定の数nが最小バイトで素数であるかどうかを判断することです。しかし、あなたのコードは、単一でなければならないのPython 2のみからなる数字で表現

  • オペレーター
  • 入力変数 n
  • 整数定数
  • 括弧

ループなし、割り当てなし、組み込み関数なし、上記のリストのみ。はい、可能です。

オペレーター

Python 2のすべての演算子のリストを次に示します。算術演算子、ビット演算子、論理演算子が含まれます。

+    adddition
-    minus or unary negation
*    multiplication
**   exponentiation, only with non-negative exponent
/    floor division
%    modulo
<<   bit shift left
>>   bit shift right
&    bitwise and
|    bitwise or
^    bitwise xor
~    bitwise not
<    less than
>    greater than
<=   less than or equals
>=   greater than or equals
==   equals
!=   does not equal

すべての中間値は整数です(または暗黙的に0と1に等しいFalse / True)。指数は負の指数では使用できません。これは浮動小数点数を生成する可能性があるためです。/Python 3とは異なり、フロア分割//は必要ないことに注意してください。

Pythonに精通していなくても、演算子はかなり直感的でなければなりません。参照演算子の優先順位については、この表、このセクションおよび以下の文法の詳細な仕様について。TIOでPython 2を実行できます

I / O

入力:n少なくとも2の正の整数。

出力:n素数の場合は1、それ以外の場合は0。TrueFalseを使用することもできます。少ないバイトが勝ちます。

コードは式であるため、スニペットになり、入力値がとして格納されていることを期待し、n必要な出力を評価します。

あなたのコードはn、システムの制限を別にして、arbitrarily意的に機能する必要があります。Pythonの整数型は無制限なので、演算子に制限はありません。ただし、コードの実行には時間がかかる場合があります。


たぶんこれにはpythonタグが必要ですか?
fəˈnɛtɪk

回答:


35

43バイト

(4**n+1)**n%4**n**2/n&2**(2*n*n+n)/-~2**n<1

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

この方法は、デニスの2番目の(削除された)答えに似ていますが、この答えは正しいと簡単に証明できます。

証明

ショートフォーム

最上位桁を(4**n+1)**n%4**n**2ベースにで割り切れないn個の次の(下位)デジットになります(すなわち、「次の数字は、」小数部分でない場合)ゼロ以外を、次いで、ビットマスクとをチェックするために実行されます奇数位置の数字がゼロ以外の場合。2nn(4**n+1)**n%4**n**2/n&2**(2*n*n+n)/-~2**n

長い形式

ましょうその基地持つ数であり、Bの表現を、すなわち、n個のB N + + 1 、B 1 + 0 、B 0、およびiが "に数字であります位置」iをベースb表現で。[an,,a1,a0]bbanbn++a1b1+a0b0aiib

  • 2**(2*n*n+n)/-~2**n=2(2n+1)n1+2n=4n2×2n1+2n=(4n21)×2n1+2n+2n1+2n

なぜなら(とN2N-1s)が整数であり、2N2n×4n211+2n=2n(2n1)×(4n)n14n1=[2n1,0,2n1,0,2n1,0]2nn 2n1、 =[2N-102N-102N-10]2N2n1+2n=02**(2*n*n+n)/-~2**n[2n1,0,2n1,0,2n1,0]2n

次に、(4 ** n + 1)** nを検討します

(4**n+1)**n=(4n+1)n=(n0)40n+(n1)41n++(nn)4n2=[(nn),0,,0,(n1),0,(n0)]2n

なので、数値を最後の 2 n桁に切り捨てます- n4n2=(2n)2n%4**n**22n(1)ですが、他のすべての二項係数が含まれます。(nn)

について/n

  • If n is a prime, the result will be [(nn1)/n,0,,0,(n1)/n,0,0]2n. All digits at odd position are zero.

  • If n is not a prime:

    Let a be the largest integer such that n(na) (n>a>0). Rewrite the dividend as

    [(nn1),0,(nn2),0,,(na+1),0,0,0,,0,0,0]2n+[(na),0,(na1),0,,(n0)]2n

    The first summand has all digits divisible by n, and the digit at position 2a1 zero.

    The second summand has its most significant digit (at position 2a) not divisible by n and (the base) 2n>n, so the quotient when dividing that by n would have the digit at position 2a1 nonzero.

    Therefore, the final result ((4**n+1)**n%4**n**2/n) should have the digit (base 2n, of course) at position 2a+1 nonzero.

Finally, the bitwise AND (&) performs a vectorized bitwise AND on the digits in base 2n (because the base is a power of 2), and because a&0=0,a&(2n1)=a for all 0a<2n, (4**n+1)**n%4**n**2/n&2**(2*n*n+n)/-~2**n is zero iff (4**n+1)**n%4**n**2/n has all digits in first n odd positions zero - which is equivalent to n being prime.


2
Would (4**n+1)**n%2**n**2/n&2**n**2/-~2**n<1 work?
Dennis

11
If it's easy to prove correct, could you include the proof in the answer? We have MathJax now, so it's relatively easy to make proofs legible, and I can't see an obvious reason for the division by n not to cause unwanted interactions between the digits base 4**n.
Peter Taylor

3
"I have discovered a truly remarkable proof of this answer which this comment is too small to contain..."
Digital Trauma

1
Suggestions for shortening the proof are welcome.
user202729

1
Nicely done! This is the same solution I had come up with. I found a couple of bytes can be cut with (4**n+1)**n%4**n**2/n<<n&4**n**2/-~2**n<1. I'm curious if this challenge is possible without bitwise operators.
xnor

6

Python 2, 56 bytes

n**(n*n-n)/(((2**n**n+1)**n**n>>n**n*~-n)%2**n**n)%n>n-2

Try it online!

This is a proof-of-concept that this challenge is doable with only arithmetic operators, in particular without bitwise |, &, or ^. The code uses bitwise and comparison operators only for golfing, and they can easily be replaced with arithmetic equivalents.

However, the solution is extremely slow, and I haven't been able to run n=6`, thanks to two-level exponents like 2nn.

The main idea is to make an expression for the factorial n!, which lets us do a Wilson's Theorem primality test (n1)!%n>n2 where % is the modulo operator.

We can make an expression for the binomial coefficient, which is made of factorials

(mn) =m!n!(mn)!

But it's not clear how to extract just one of these factorials. The trick is to hammer apart n! by making m really huge.

(mn) =m(m1)(mn+1)n!=mnn!(11m)(12m)(1n1m)

So, if we let c be the product (11m)(12m)(1n1m), we have

n!=mn(mn)c

If we could just ignore c, we'd be done. The rest of this post is looking how large we need to make m to be able to do this.

Note that c approaches 1 from below as m. We just need to make m huge enough that omitting c gives us a value with integer part n! so that we may compute

n!=mn(mn)

For this, it suffices to have 1c<1/n! to avoid the ratio passing the next integer n!+1.

Observe that c is a product of n terms of which the smallest is (1n1m). So, we have

c>(1n1m)n>1n1mn>1n2m,

which means 1c<n2m. Since we're looking to have 1c<1/n!, it suffices to take mn!n2.

In the code, we use m=nn. Since Wilson's Theorem uses (n1)!, we actually only need m(n1)!(n1)2. It's easy to see that m=nn satisfies the bound for the small values and quickly outgrows the right hand side asymptotically, say with Stirling's approximation.


3

This answer doesn't use any number-theoretic cleverness. It spams Python's bitwise operators to create a manual "for loop", checking all pairs 1i,j<n to see whether i×j=n.

Python 2, way too many bytes (278 thanks to Jo King in the comments!)

((((((2**(n*n)/(2**n-1)**2)*(2**((n**2)*n)/(2**(n**2)-1)**2))^((n*((2**(n*n-n)/(2**n-1))*(2**((n**2)*(n-1))/(2**n**2-1))))))-((2**(n*n-n)/(2**n-1))*(2**((n**2)*(n-1))/(2**(n**2)-1))))&(((2**(n*(n-1))/(2**n-1))*(2**((n**2)*(n-1))/(2**(n**2)-1)))*(2**(n-1)))==0))|((1<n<6)&(n!=4))

Try it online!

This is a lot more bytes than the other answers, so I'm leaving it ungolfed for now. The code snippet below contains functions and variable assignment for clarity, but substitution turns isPrime(n) into a single Python expression.

def count(k, spacing):
    return 2**(spacing*(k+1))/(2**spacing - 1)**2
def ones(k, spacing):
    return 2**(spacing*k)/(2**spacing - 1)

def isPrime(n):
    x = count(n-1, n)
    y = count(n-1, n**2)
    onebits = ones(n-1, n) * ones(n-1, n**2)
    comparison = n*onebits
    difference = (x*y) ^ (comparison)
    differenceMinusOne = difference - onebits
    checkbits = onebits*(2**(n-1))
    return (differenceMinusOne & checkbits == 0 and n>1)or 1<n<6 and n!=4

Why does it work?

I'll do the same algorithm here in base 10 instead of binary. Look at this neat fraction:

1.09992=1.002003004005

If we put a large power of 10 in the numerator and use Python's floor division, this gives an enumeration of numbers. For example, 1015/(9992)=1002003004 with floor division, enumerating the numbers 1,2,3,4.

Let's say we multiply two numbers like this, with different spacings of zeroes. I'll place commas suggestively in the product.

1002003004×1000000000002000000000003000000000004=
1002003004,002004006008,003006009012,004008012016

The product enumerates, in three-digit sequences, the multiplication table up to 4 times 4. If we want to check whether the number 5 is prime, we just have to check whether 005 appears anywhere in that product.

To do that, we XOR the above product by the number 005005005005, and then subtract the number 001001001001. Call the result d. If 005 appeared in the multiplication table enumeration, it will cause the subtraction to carry over and put 999 in the corresponding place in d.

To test for this overflow, we compute an AND of d and the number 900900900900. The result is zero if and only if 5 is prime.


1
A quick print of the expression puts this at 278 bytes (though I'm sure a lot of the parenthesises aren't necessary)
Jo King
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.