Asallık test formülü


30

Amacınız verilen bir sayının nen az baytta asal olup olmadığını belirlemektir . Ancak, kodunuz yalnızca aşağıdakilerden oluşan sayılar üzerinde tek bir Python 2 ifadesi olmalıdır

  • operatörler
  • giriş değişkeni n
  • tamsayı sabitleri
  • parantez

Döngü yok, atama yok, yerleşik işlev yok, yalnızca yukarıda listelenenleri. Evet mümkün.

Operatörler

İşte Python 2'deki aritmetik, bitsel ve mantıksal işleçleri içeren tüm işleçlerin bir listesi :

+    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

Tüm ara değerler tamsayılar (veya 0 ve 1'e tamamen eşit olan False / True). Üfleme negatif kayanlarla kullanılamaz, çünkü bunlar yüzebilir. Not /Python 3 farklı olarak zeminden bölünmesini yapar, böylece //gerekli değildir.

Python'u tanımasanız bile, operatörler oldukça sezgisel olmalıdır. Dilbilgisinin ayrıntılı bir belirtimi için operatör önceliği ve bu bölüm ve altındaki bu tabloya bakın . Şunları yapabilirsiniz TIO üzerinde Python 2 koşmak .

I / O

Giriş:n En az 2 olan pozitif bir tamsayı .

Çıktı: Eğer nasal ise 1 , aksi takdirde 0. Trueve Falseayrıca kullanılabilir. En az bayt kazanır.

Kodunuz bir ifade olduğundan, bir snippet olacaktır, giriş değerini olarak depolanan nve istenen çıktısını değerlendirir.

Kodunuz, nkeyfi olarak büyük, bir kenara sistem sınırları için çalışması gerekir . Python'un tam sayı türü sınırsız olduğundan, operatörlerde sınır yoktur. Kodunuzun çalışması uzun sürebilir.


Belki bu python etiketi olmalı?
f Augnɛtɪk

Yanıtlar:


35

43 bayt

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

Çevrimiçi deneyin!

Yöntem Dennis'in ikinci (silinmiş) cevabına benzer, ancak bu cevabın doğru olması daha kolaydır.

Kanıt

Kısa form

En yüksek değer basamağı (4**n+1)**n%4**n**2tabanında tarafından bölünebilir değildir n sonraki (daha az önemli) basamağını yapacak sonra (yani "bir sonraki basamak" fraksiyonel kısmında değilse) Sıfır dışındaki bir bit maskesi ile2nn(4**n+1)**n%4**n**2/n&2**(2*n*n+n)/-~2**n check yürütüldüğünde Tek pozisyondaki herhangi bir rakam sıfır değilse.

Uzun formu

[an,,a1,a0]b be the number having that base b representation, i.e., anbn++a1b1+a0b0, and ai be the digit at "position" i in base b representation.

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

Because 2n×4n211+2n=2n(2n1)×(4n)n14n1=[2n1,0,2n1,0,2n1,0]2n (with n 2n1s) is an integer, and 2n1+2n=0, 2**(2*n*n+n)/-~2**n = [2n1,0,2n1,0,2n1,0]2n.

Next, consider

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

4n2=(2n)2n, so %4**n**2 will truncate the number to 2n last digits - that excludes the (nn) (which is 1) but include all other binomial coefficients.

About /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
Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.