Jump to content

AKS test for primes: Difference between revisions

m (Added Delphi reference to Pascal code)
Line 2,525:
primes under 50
{1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47}</pre>
 
=={header|Nim}==
<lang Nim>
from math import binom
import strutils
 
# Table of unicode superscript characters.
const Exponents: array[0..9, string] = ["⁰", "¹", "²", "³", "⁴", "⁵", "⁶", "⁷", "⁸", "⁹"]
 
iterator coeffs(n: int): int =
## Yield the coefficients of the expansion of (x - 1)ⁿ.
var sign = 1
for k in 0..n:
yield binom(n, k) * sign
sign = -sign
 
iterator polyExpansion(n: int): tuple[c, e: int] =
## Yield the coeeficients and the exponents of the expansion of (x - 1)ⁿ.
var e = n
for c in coeffs(n):
yield(c, e)
dec e
 
proc termString(c, e: int): string =
## Return the string for the terme c * e^n.
if e == 0:
result.addInt(c)
else:
if c != 1:
result.addInt(c)
result.add('x')
if e != 1:
result.add(Exponents[e])
 
proc polyString(n: int): string =
## Return the string for the expansion of (x - 1)ⁿ.
for (c, e) in polyExpansion(n):
if c < 0:
result.add(" - ")
elif e != n:
result.add(" + ")
result.add(termString(abs(c), e))
 
proc isPrime(n: int): bool =
## Check if the anumber is prime using the polynome expansion.
result = true
for (c, e) in polyExpansion(n):
if e in 1..(n-1): # xⁿ and 1 are eliminated by the subtraction.
if c mod n != 0:
return false
 
#---------------------------------------------------------------------------------------------------
 
echo "Polynome expansions:"
for p in 0..9:
echo "(x - 1)$1 = $2".format(Exponents[p], polyString(p))
 
var primes: string
for p in 2..34:
if p.isPrime():
primes.addSep(", ", 0)
primes.addInt(p)
echo "\nPrimes under 35: ", primes
 
for p in 35..50:
if p.isPrime():
primes.add(", ")
primes.addInt(p)
echo "\nPrimes under 50: ", primes
</lang>
 
{{out}}
<pre>
Polynome expansions:
(x - 1)⁰ = 1
(x - 1)¹ = x - 1
(x - 1)² = x² - 2x + 1
(x - 1)³ = x³ - 3x² + 3x - 1
(x - 1)⁴ = x⁴ - 4x³ + 6x² - 4x + 1
(x - 1)⁵ = x⁵ - 5x⁴ + 10x³ - 10x² + 5x - 1
(x - 1)⁶ = x⁶ - 6x⁵ + 15x⁴ - 20x³ + 15x² - 6x + 1
(x - 1)⁷ = x⁷ - 7x⁶ + 21x⁵ - 35x⁴ + 35x³ - 21x² + 7x - 1
(x - 1)⁸ = x⁸ - 8x⁷ + 28x⁶ - 56x⁵ + 70x⁴ - 56x³ + 28x² - 8x + 1
(x - 1)⁹ = x⁹ - 9x⁸ + 36x⁷ - 84x⁶ + 126x⁵ - 126x⁴ + 84x³ - 36x² + 9x - 1
 
Primes under 35: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31
 
Primes under 50: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47
</pre>
 
=={{header|Objeck}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.