def is_perf_pow(n):
for a in xrange(2, int((sqrt(n))) + 1):
for b in xrange(2, log(n, a) + 1):
res = a^b
if (res > n):
break
if (n == res):
return "composite"
return "not perfect power"
def is_perf_pow2(n):
a = 2
a_lim = floor(sqrt(n)) + 1
while a < a_lim:
b = 2
b_lim = log(n, a) + 1
while b < b_lim:
res = a^b
if res > n:
break
if n == res:
return "composite"
b = b + 1
a = a + 1
return "not perfect power"
def ord_mod(n, r):
"""
Given the parameters (n, r), returns the order of n modulo r.
"""
if r < 2:
return 'mod must be greater than 2'
if gcd(n, r) != 1:
return "n and r must be coprime!"
res = 0
i = 1
while res != 1:
res = n^i % r
i = i + 1
return i - 1
R.<x> = ZZ[]
def smallest_r(n):
"""
Finding the smallest r such that ord_mod(n, r) > log(n, 2)^2
"""
ord = 0
r = floor(log(n, 2)^2)
while ord <= log(n, 2)^2:
r = r + 1
if gcd(r,n) == 1:
ord = ord_mod(n,r)
return r
def polynom_mod(r, n):
R.<x> = Integers(n)[]
for a in xrange(1, ZZ(floor((sqrt(euler_phi(r)) * log(n, 2))))):
left_pol = (x + a)^n
if left_pol.quo_rem(x^r - 1)[1] != (x^(n%r) + a):
return "composite"
return "prime"
def aks(n):
pow = is_perf_pow2(n)
if pow == "composite":
return pow
r = smallest_r(n)
for a in range(2, min(r, (n/2) + 1)):
if gcd(a, n) > 1:
return "composite"
if n <= r:
return "prime"
else:
p = polynom_mod(r, n)
return p
@interact
def _(n = input_box(2)): print(aks(n))