本文整理汇总了Python中sage.all.factor函数的典型用法代码示例。如果您正苦于以下问题:Python factor函数的具体用法?Python factor怎么用?Python factor使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了factor函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: dirichlet_series_coeffs
def dirichlet_series_coeffs(self, prec, eps=1e-10):
"""
Return the coefficients of the Dirichlet series representation
of self, up to the given precision.
INPUT:
- prec -- positive integer
- eps -- None or a positive real; any coefficient with absolute
value less than eps is set to 0.
"""
# Use multiplicativity to compute the Dirichlet series
# coefficients, then make a DirichletSeries object.
zero = RDF(0)
coeffs = [RDF(0),RDF(1)] + [None]*(prec-2)
from sage.all import log, floor # TODO: slow
# prime-power indexed coefficients
for p in prime_range(2, prec):
B = floor(log(prec, p)) + 1
series = self._local_series(p, B)
p_pow = p
for i in range(1, B):
coeffs[p_pow] = series[i] if (eps is None or abs(series[i])>eps) else zero
p_pow *= p
# non-prime-powers
from sage.all import factor
for n in range(2, prec):
if coeffs[n] is None:
a = prod(coeffs[p**e] for p, e in factor(n))
coeffs[n] = a if (eps is None or abs(a) > eps) else zero
return coeffs
示例2: list_to_factored_poly_otherorder
def list_to_factored_poly_otherorder(s):
if len(s) == 1:
return str(s[0])
sfacts = factor(PolynomialRing(ZZ, 'T')(s))
sfacts_fc = [[v[0],v[1]] for v in sfacts]
if sfacts.unit() == -1:
sfacts_fc[0][0] *= -1
outstr = ''
for v in sfacts_fc:
vcf = v[0].list()
started = False
if len(sfacts) > 1 or v[1] > 1:
outstr += '('
for i in range(len(vcf)):
if vcf[i] <> 0:
if started and vcf[i] > 0:
outstr += '+'
started = True
if i == 0:
outstr += str(vcf[i])
else:
if abs(vcf[i]) <> 1:
outstr += str(vcf[i])
elif vcf[i] == -1:
outstr += '-'
if i == 1:
outstr += 'T'
elif i > 1:
outstr += 'T^{' + str(i) + '}'
if len(sfacts) > 1 or v[1] > 1:
outstr += ')'
if v[1] > 1:
outstr += '^{' + str(v[1]) + '}'
return outstr
示例3: hecke_charpoly
def hecke_charpoly(self, m, var="x", algorithm='linbox'):
p, i = factor(m)[0]
if not (ZZ(m).is_prime_power() and 0 < i < 3):
raise RuntimeError("m must be a prime or the square of a prime.")
if i == 1:
return self._hecke_tp_charpoly(p, var=var, algorithm=algorithm)
if i == 2:
return self._hecke_tp2_charpoly(p, var=var, algorithm=algorithm)
示例4: myfunc
def myfunc(inp, n):
fn = list(factor(inp))
pvals = [[localfactorsa[self.any_prime_to_cc_index(z[0]) - 1], z[1]] for z in fn]
# -1 is the marker that the prime divides the conductor
for j in range(len(pvals)):
if pvals[j][0] < 0:
return -1
pvals = sum([z[0] * z[1] for z in pvals])
return pvals % n
示例5: ll_common_denominator
def ll_common_denominator(f):
"""For a polynomial f with fractional coefficients, write out the
polynomial such that there is only a single denominator."""
# f should be a polynomial
if not is_Polynomial(f):
return ll_raw(f)
# first determine the lcm of the denominators of the coefficients
cd = reduce(lcm, [c.denominator() for c in f])
if is_Polynomial(cd) and cd.degree() > 0:
return "\\frac{" + ll_raw(cd * f) + "}{" + ll_raw(factor(cd)) + "}"
else:
return ll_raw(f)
示例6: id_dirichlet
def id_dirichlet(fun, N, n):
N = Integer(N)
if N == 1:
return (1, 1)
p2 = valuation(N, 2)
N2 = 2 ** p2
Nodd = N / N2
Nfact = list(factor(Nodd))
# print "n = "+str(n)
# for j in range(20):
# print "chi(%d) = e(%d/%d)"%(j+2, fun(j+2,n), n)
plist = [z[0] for z in Nfact]
ppows = [z[0] ** z[1] for z in Nfact]
ppows2 = list(ppows)
idems = [1 for z in Nfact]
proots = [primitive_root(z) for z in ppows]
# Get CRT idempotents
if p2 > 0:
ppows2.append(N2)
for j in range(len(plist)):
exps = [1 for z in idems]
if p2 > 0:
exps.append(1)
exps[j] = proots[j]
idems[j] = crt(exps, ppows2)
idemvals = [fun(z, n) for z in idems]
# now normalize to right root of unity base
idemvals = [idemvals[j] * euler_phi(ppows[j]) / n for j in range(len(idemvals))]
ans = [Integer(mod(proots[j], ppows[j]) ** idemvals[j]) for j in range(len(proots))]
ans = crt(ans, ppows)
# There are cases depending on 2-part of N
if p2 == 0:
return (N, ans)
if p2 == 1:
return (N, crt([1, ans], [2, Nodd]))
if p2 == 2:
my3 = crt([3, 1], [N2, Nodd])
if fun(my3, n) == 0:
return (N, crt([1, ans], [4, Nodd]))
else:
return (N, crt([3, ans], [4, Nodd]))
# Final case 2^3 | N
my5 = crt([5, 1], [N2, Nodd])
test1 = fun(my5, n) * N2 / 4 / n
test1 = Integer(mod(5, N2) ** test1)
minusone = crt([-1, 1], [N2, Nodd])
test2 = (fun(minusone, n) * N2 / 4 / n) % (N2 / 4)
if test2 > 0:
test1 = Integer(mod(-test1, N2))
return (N, crt([test1, ans], [N2, Nodd]))
示例7: pohlighellman
def pohlighellman(g, h):
phi = g.multiplicative_order()
factors = factor(phi)
chinese_pairs = []
for pi, ei in factors:
n = phi / (pi**ei)
print("testing n = %s" % n)
hn = h**n
print(("Searching h^%d in subgroup "
"g^%d using Baby-step giant-step") % (n, n))
a = babystepgiantstep(g**n, hn)
print("Found g^(%s * %s) == %s" % (n, a, hn))
chinese_pairs.append([a, pi**ei])
return crt(*map(list, zip(*chinese_pairs)))
示例8: pohlighellman
def pohlighellman(g, h):
phi = g.multiplicative_order()
factors = factor(phi)
chinese_pairs = []
for pi, ei in factors:
n = phi / (pi ** ei)
print("testing n = %s" % n)
hn = h ** n
print("h^%s = %s" % (n, hn))
for i in range(pi ** ei):
print("Testing g^(%s * %s) == %s" % (i, n, hn))
if g ** (n * i) == hn:
print("Found x mod %s = %s" % (pi ** ei, i))
chinese_pairs.append([i, pi ** ei])
break
return crt(*map(list, zip(*chinese_pairs)))
示例9: compute_dirichlet_series
def compute_dirichlet_series(p_list, PREC):
''' computes the dirichlet series for a Lfunction_SMF2_scalar_valued
'''
# p_list is a list of pairs (p,y) where p is a prime and y is the list of roots of the Euler factor at x
LL = [0] * PREC
# create an empty list of the right size and now populate it with the powers of p
for (p, y) in p_list:
# FIXME p_prec is never used, but perhaps it should be?
# p_prec = log(PREC) / log(p) + 1
ep = euler_p_factor(y, PREC)
for n in range(ep.prec()):
if p ** n < PREC:
LL[p ** n] = ep.coefficients()[n]
for i in range(1, PREC):
f = factor(i)
if len(f) > 1: # not a prime power
LL[i] = prod([LL[p ** e] for (p, e) in f])
return LL[1:]
示例10: __init__
def __init__(self, K, N_max=10**5):
"""
Compute J working over the field K.
"""
self.N_max = N_max
self.K = K
from sage.all import prime_powers, factor
PP = prime_powers(N_max+1)[1:]
n = len(PP)
self.a = [K(0)]*n
self.s = [K(0)]*n
self.pv = [0]*n
i = 0
for pv in PP:
F = factor(pv)
p, v = F[0]
self.pv[i] = K(pv)
logp = K(p).log()
self.a[i] = logp/K(pv).sqrt()
self.s[i] = v*logp
i += 1
示例11: coefficient_n_recursive
def coefficient_n_recursive(self, n):
r"""
Reimplement the recursive algorithm in sage modular/hecke/module.py
We do this because of a bug in sage with .eigenvalue()
"""
from sage.all import factor
ev = self.eigenvalues
c2 = self._coefficients.get(2)
if c2 is not None:
K = c2.parent()
else:
if ev.max_coefficient_in_db() >= 2:
if not ev.has_eigenvalue(2):
ev.init_dynamic_properties()
else:
raise StopIteration,"Newform does not have eigenvalue a(2)!"
self._coefficients[2]=ev[2]
K = ev[2].parent()
prod = K(1)
if K.absolute_degree()>1 and K.is_relative():
KZ = K.base_field()
else:
KZ = K
#emf_logger.debug("K= {0}".format(K))
F = factor(n)
for p, r in F:
#emf_logger.debug("parent_char_val[{0}]={1}".format(p,self.parent.character_used_in_computation.value(p)))
#emf_logger.debug("char_val[{0}]={1}".format(p,self.character.value(p)))
(p, r) = (int(p), int(r))
pr = p**r
cp = self._coefficients.get(p)
if cp is None:
if ev.has_eigenvalue(p):
cp = ev[p]
elif ev.max_coefficient_in_db() >= p:
ev.init_dynamic_properties()
cp = ev[p]
#emf_logger.debug("c{0} = {1}, parent={2}".format(p,cp,cp.parent()))
if cp is None:
raise IndexError,"p={0} is outside the range of computed primes (primes up to {1})! for label:{2}".format(p,max(ev.primes()),self.label)
if self._coefficients.get(pr) is None:
if r == 1:
c = cp
else:
# a_{p^r} := a_p * a_{p^{r-1}} - eps(p)p^{k-1} a_{p^{r-2}}
apr1 = self.coefficient_n_recursive(pr//p)
#ap = self.coefficient_n_recursive(p)
apr2 = self.coefficient_n_recursive(pr//(p*p))
val = self.character.value(p)
if val == 0:
c = cp*apr1
else:
eps = KZ(val)
c = cp*apr1 - eps*(p**(self.weight-1)) * apr2
#emf_logger.debug("c({0})={1}".format(pr,c))
#ev[pr]=c
self._coefficients[pr]=c
try:
prod *= K(self._coefficients[pr])
except:
if hasattr(self._coefficients[pr],'vector'):
if len(self._coefficients[pr].vector()) == len(K.power_basis()):
prod *= K(self._coefficients[pr].vector())
else:
emf_logger.debug("vec={0}".format(self._coefficients[pr].vector()))
raise ArithmeticError,"Wrong size of vectors!"
else:
raise ArithmeticError,"Can not compute product of coefficients!"
return prod
示例12: make_curve
def make_curve(self):
# To start with the data fields of self are just those from
# the database. We need to reformat these, construct the
# and compute some further (easy) data about it.
#
# Weierstrass equation
data = self.data = {}
disc = ZZ(self.disc_sign) * ZZ(self.disc_key[3:])
# to deal with disc_key, uncomment line above and remove line below
#disc = ZZ(self.disc_sign) * ZZ(self.abs_disc)
data['disc'] = disc
data['cond'] = ZZ(self.cond)
data['min_eqn'] = self.min_eqn
data['min_eqn_display'] = list_to_min_eqn(self.min_eqn)
data['disc_factor_latex'] = web_latex(factor(data['disc']))
data['cond_factor_latex'] = web_latex(factor(int(self.cond)))
data['aut_grp'] = groupid_to_meaningful(self.aut_grp)
data['geom_aut_grp'] = groupid_to_meaningful(self.geom_aut_grp)
data['igusa_clebsch'] = [ZZ(a) for a in self.igusa_clebsch]
data['igusa'] = igusa_clebsch_to_igusa(data['igusa_clebsch'])
data['g2'] = igusa_to_g2(data['igusa'])
data['ic_norm'] = normalize_invariants(data['igusa_clebsch'],[1,2,3,5])
data['igusa_norm'] = normalize_invariants(data['igusa'],[1,2,3,4,5])
data['ic_norm_factor_latex'] = [web_latex(zfactor(i)) for i in data['ic_norm']]
data['igusa_norm_factor_latex'] = [web_latex(zfactor(j)) for j in data['igusa_norm']]
data['num_rat_wpts'] = ZZ(self.num_rat_wpts)
data['two_selmer_rank'] = ZZ(self.two_selmer_rank)
if len(self.torsion) == 0:
data['tor_struct'] = '\mathrm{trivial}'
else:
tor_struct = [ZZ(a) for a in self.torsion]
data['tor_struct'] = ' \\times '.join(['\Z/{%s}\Z' % n for n in tor_struct])
isogeny_class = db_g2c().isogeny_classes.find_one({'label' : isog_label(self.label)})
end_data = get_end_data(isogeny_class)
for key in end_data.keys():
data[key] = end_data[key]
x = self.label.split('.')[1]
self.make_code_snippets()
self.friends = [
('Isogeny class %s' % isog_label(self.label), url_for(".by_double_iso_label", conductor = self.cond, iso_label = x)),
('L-function', url_for("l_functions.l_function_genus2_page", cond=self.cond,x=x)),
('Twists',url_for(".index_Q", ic0 = self.igusa_clebsch[0], ic1 = self.igusa_clebsch[1],ic2 = self.igusa_clebsch[2],ic3 = self.igusa_clebsch[3])),
#('Twists2',url_for(".index_Q", igusa_clebsch = str(self.igusa_clebsch))) #doesn't work.
#('Siegel modular form someday', '.')
]
self.downloads = [
('Download all stored data', '.')]
iso = self.label.split('.')[1]
num = '.'.join(self.label.split('.')[2:4])
self.plot = encode_plot(eqn_list_to_curve_plot(self.min_eqn))
self.plot_link = '<img src="%s" width="200" height="150"/>' % self.plot
self.properties = [('Label', self.label),
(None, self.plot_link),
('Conductor','%s' % self.cond),
('Discriminant', '%s' % data['disc']),
('Invariants', '%s </br> %s </br> %s </br> %s'% tuple(data['ic_norm'])),
('Sato-Tate group', '\(%s\)' % data['st_group_name']),
('\(%s\)' % data['real_geom_end_alg_name'][0],'\(%s\)' % data['real_geom_end_alg_name'][1]),
('\(\mathrm{GL}_2\)-type','%s' % data['is_gl2_type_name'])]
self.title = "Genus 2 Curve %s" % (self.label)
self.bread = [
('Genus 2 Curves', url_for(".index")),
('$\Q$', url_for(".index_Q")),
('%s' % self.cond, url_for(".by_conductor", conductor=self.cond)),
('%s' % iso, url_for(".by_double_iso_label", conductor=self.cond, iso_label=iso)),
('Genus 2 curve %s' % num, url_for(".by_g2c_label", label=self.label))]
示例13: main5
def main5():
n = 32295194023343
e = 29468811804857
d = 11127763319273
print(crack_given_decrypt(n, e * d - 1))
print(factor(n))
示例14: list_to_factored_poly
def list_to_factored_poly(s):
return str(factor(PolynomialRing(ZZ, 't')(s))).replace('*','')
示例15: find_curve
#.........这里部分代码省略.........
P = ZZ(P)
p = ZZ(P)
Fdisc = ZZ(1)
if NE % (P*DB) != 0:
raise ValueError,'Conductor (NE) should be divisible by P*DB'
Ncartan = kwargs.get('Ncartan',None)
Np = NE / (P * DB)
if Ncartan is not None:
Np = Np / Ncartan**2
if use_ps_dists is None:
use_ps_dists = False # More efficient our own implementation
if not p.is_prime():
raise ValueError,'P (= %s) should be a prime, of inertia degree 1'%P
working_prec = max([2 * prec + 10, 100])
sgninfty = 'plus' if sign_at_infinity == 1 else 'minus'
fname = 'moments_%s_%s_%s_%s_%s_%s.sobj'%(Fdisc,p,DB,NE,sgninfty,prec)
if outfile == 'log':
outfile = '%s_%s_%s_%s_%s.log'%(P,NE,sgninfty,prec,datetime.datetime.now().strftime("%Y%m%d-%H%M%S"))
outfile = outfile.replace('/','div')
outfile = '/tmp/findcurve_' + outfile
if F != QQ and ramification_at_infinity is None:
if F.signature()[0] > 1:
if F.signature()[1] == 1:
ramification_at_infinity = F.real_places(prec = Infinity) # Totally 'definite'
else:
raise ValueError,'Please specify the ramification at infinity'
elif F.signature()[0] == 1:
if len(F.ideal(DB).factor()) % 2 == 0:
ramification_at_infinity = [] # Split at infinity
else:
ramification_at_infinity = F.real_places(prec = Infinity) # Ramified at infinity
else:
ramification_at_infinity = None
if outfile is not None:
print("Partial results will be saved in %s"%outfile)
if initial_data is not None:
G,phiE = initial_data
else:
# Define the S-arithmetic group
try:
if F == QQ:
abtuple = QuaternionAlgebra(DB).invariants()
else:
abtuple = quaternion_algebra_invariants_from_ramification(F,DB,ramification_at_infinity)
G = BigArithGroup(P, abtuple, Np, use_sage_db = use_sage_db, grouptype = grouptype, magma = magma, seed = magma_seed, timeout = timeout, use_shapiro = use_shapiro, nscartan = Ncartan)
except RuntimeError as e:
if quit_when_done:
magma.quit()
mystr = str(e)
if len(mystr) > 30:
mystr = mystr[:14] + ' ... ' + mystr[-14:]
if return_all:
return ['Error when computing G: ' + mystr]
else:
return 'Error when computing G: ' + mystr
# Define phiE, the cohomology class associated to the system of eigenvalues.
Coh = ArithCoh(G)