Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagesmc
Path: blob/master/src/sage/rings/arith.py
8817 views
1
"""
2
Miscellaneous arithmetic functions
3
"""
4
#*****************************************************************************
5
# Copyright (C) 2006 William Stein <[email protected]>
6
#
7
# Distributed under the terms of the GNU General Public License (GPL)
8
# as published by the Free Software Foundation; either version 2 of
9
# the License, or (at your option) any later version.
10
# http://www.gnu.org/licenses/
11
#*****************************************************************************
12
13
14
import math
15
import sys
16
import sage.misc.misc as misc
17
from sage.libs.pari.all import pari
18
import sage.libs.flint.arith as flint_arith
19
20
from sage.rings.rational_field import QQ
21
import sage.rings.rational
22
import sage.rings.complex_field
23
import sage.rings.complex_number
24
import sage.rings.real_mpfr
25
from sage.structure.element import parent
26
from sage.misc.misc import prod, union
27
from sage.rings.real_mpfi import RealIntervalField
28
29
import fast_arith
30
31
from integer_ring import ZZ
32
import integer
33
34
##################################################################
35
# Elementary Arithmetic
36
##################################################################
37
38
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False):
39
"""
40
Returns a polynomial of degree at most `degree` which is
41
approximately satisfied by the number `z`. Note that the returned
42
polynomial need not be irreducible, and indeed usually won't be if
43
`z` is a good approximation to an algebraic number of degree less
44
than `degree`.
45
46
You can specify the number of known bits or digits of `z` with
47
``known_bits=k`` or ``known_digits=k``. PARI is then told to
48
compute the result using `0.8k` of these bits/digits. Or, you can
49
specify the precision to use directly with ``use_bits=k`` or
50
``use_digits=k``. If none of these are specified, then the precision
51
is taken from the input value.
52
53
A height bound may be specified to indicate the maximum coefficient
54
size of the returned polynomial; if a sufficiently small polynomial
55
is not found, then ``None`` will be returned. If ``proof=True`` then
56
the result is returned only if it can be proved correct (i.e. the
57
only possible minimal polynomial satisfying the height bound, or no
58
such polynomial exists). Otherwise a ``ValueError`` is raised
59
indicating that higher precision is required.
60
61
ALGORITHM: Uses LLL for real/complex inputs, PARI C-library
62
``algdep`` command otherwise.
63
64
Note that ``algebraic_dependency`` is a synonym for ``algdep``.
65
66
INPUT:
67
68
69
- ``z`` - real, complex, or `p`-adic number
70
71
- ``degree`` - an integer
72
73
- ``height_bound`` - an integer (default: ``None``) specifying the maximum
74
coefficient size for the returned polynomial
75
76
- ``proof`` - a boolean (default: ``False``), requires height_bound to be set
77
78
79
EXAMPLES::
80
81
sage: algdep(1.888888888888888, 1)
82
9*x - 17
83
sage: algdep(0.12121212121212,1)
84
33*x - 4
85
sage: algdep(sqrt(2),2)
86
x^2 - 2
87
88
This example involves a complex number::
89
90
sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z
91
0.500000000000000 + 0.866025403784439*I
92
sage: p = algdep(z, 6); p
93
x^3 + 1
94
sage: p.factor()
95
(x + 1) * (x^2 - x + 1)
96
sage: z^2 - z + 1
97
0.000000000000000
98
99
This example involves a `p`-adic number::
100
101
sage: K = Qp(3, print_mode = 'series')
102
sage: a = K(7/19); a
103
1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20)
104
sage: algdep(a, 1)
105
19*x - 7
106
107
These examples show the importance of proper precision control. We
108
compute a 200-bit approximation to `sqrt(2)` which is wrong in the
109
33'rd bit::
110
111
sage: z = sqrt(RealField(200)(2)) + (1/2)^33
112
sage: p = algdep(z, 4); p
113
227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088
114
sage: factor(p)
115
227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088
116
sage: algdep(z, 4, known_bits=32)
117
x^2 - 2
118
sage: algdep(z, 4, known_digits=10)
119
x^2 - 2
120
sage: algdep(z, 4, use_bits=25)
121
x^2 - 2
122
sage: algdep(z, 4, use_digits=8)
123
x^2 - 2
124
125
Using the ``height_bound`` and ``proof`` parameters, we can see that
126
`pi` is not the root of an integer polynomial of degree at most 5
127
and coefficients bounded above by 10::
128
129
sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None
130
True
131
132
For stronger results, we need more precicion::
133
134
sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None
135
Traceback (most recent call last):
136
...
137
ValueError: insufficient precision for non-existence proof
138
sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None
139
True
140
141
sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None
142
Traceback (most recent call last):
143
...
144
ValueError: insufficient precision for non-existence proof
145
sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None
146
True
147
148
We can also use ``proof=True`` to get positive results::
149
150
sage: a = sqrt(2) + sqrt(3) + sqrt(5)
151
sage: algdep(a.n(), 8, height_bound=1000, proof=True)
152
Traceback (most recent call last):
153
...
154
ValueError: insufficient precision for uniqueness proof
155
sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f
156
x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576
157
sage: f(a).expand()
158
0
159
160
TESTS::
161
162
sage: algdep(complex("1+2j"), 4)
163
x^2 - 2*x + 5
164
"""
165
if proof and not height_bound:
166
raise ValueError, "height_bound must be given for proof=True"
167
168
x = ZZ['x'].gen()
169
170
if isinstance(z, (int, long, integer.Integer)):
171
if height_bound and abs(z) >= height_bound:
172
return None
173
return x - ZZ(z)
174
175
degree = ZZ(degree)
176
177
if isinstance(z, (sage.rings.rational.Rational)):
178
if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound:
179
return None
180
return z.denominator()*x - z.numerator()
181
182
if isinstance(z, float):
183
z = sage.rings.all.RR(z)
184
elif isinstance(z, complex):
185
z = sage.rings.all.CC(z)
186
187
if isinstance(z, (sage.rings.real_mpfr.RealNumber,
188
sage.rings.complex_number.ComplexNumber)):
189
190
log2_10 = 3.32192809488736
191
192
prec = z.prec() - 6
193
if known_digits is not None:
194
known_bits = known_digits * log2_10
195
if known_bits is not None:
196
use_bits = known_bits * 0.8
197
if use_digits is not None:
198
use_bits = use_digits * log2_10
199
if use_bits is not None:
200
prec = int(use_bits)
201
202
is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber)
203
n = degree+1
204
from sage.matrix.all import matrix
205
M = matrix(ZZ, n, n+1+int(is_complex))
206
r = ZZ(1) << prec
207
M[0, 0] = 1
208
M[0,-1] = r
209
for k in range(1, degree+1):
210
M[k,k] = 1
211
r *= z
212
if is_complex:
213
M[k, -1] = r.real().round()
214
M[k, -2] = r.imag().round()
215
else:
216
M[k, -1] = r.round()
217
LLL = M.LLL(delta=.75)
218
coeffs = LLL[0][:n]
219
if height_bound:
220
def norm(v):
221
# norm on an integer vector invokes Integer.sqrt() which tries to factor...
222
from sage.rings.real_mpfi import RIF
223
return v.change_ring(RIF).norm()
224
if max(abs(a) for a in coeffs) > height_bound:
225
if proof:
226
# Given an LLL reduced basis $b_1, ..., b_n$, we only
227
# know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$.
228
if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound:
229
raise ValueError, "insufficient precision for non-existence proof"
230
return None
231
elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound):
232
raise ValueError, "insufficient precision for uniqueness proof"
233
if coeffs[degree] < 0:
234
coeffs = -coeffs
235
f = list(coeffs)
236
237
elif proof or height_bound:
238
raise NotImplementedError, "proof and height bound only implemented for real and complex numbers"
239
240
else:
241
y = pari(z)
242
f = y.algdep(degree)
243
244
return x.parent()(f)
245
246
247
algebraic_dependency = algdep
248
249
def bernoulli(n, algorithm='default', num_threads=1):
250
r"""
251
Return the n-th Bernoulli number, as a rational number.
252
253
INPUT:
254
255
- ``n`` - an integer
256
- ``algorithm``:
257
258
- ``'default'`` - (default) use 'pari' for n <= 30000, and 'bernmm' for
259
n > 30000 (this is just a heuristic, and not guaranteed to be optimal
260
on all hardware)
261
- ``'pari'`` - use the PARI C library
262
- ``'gap'`` - use GAP
263
- ``'gp'`` - use PARI/GP interpreter
264
- ``'magma'`` - use MAGMA (optional)
265
- ``'bernmm'`` - use bernmm package (a multimodular algorithm)
266
267
- ``num_threads`` - positive integer, number of
268
threads to use (only used for bernmm algorithm)
269
270
EXAMPLES::
271
272
sage: bernoulli(12)
273
-691/2730
274
sage: bernoulli(50)
275
495057205241079648212477525/66
276
277
We demonstrate each of the alternative algorithms::
278
279
sage: bernoulli(12, algorithm='gap')
280
-691/2730
281
sage: bernoulli(12, algorithm='gp')
282
-691/2730
283
sage: bernoulli(12, algorithm='magma') # optional - magma
284
-691/2730
285
sage: bernoulli(12, algorithm='pari')
286
-691/2730
287
sage: bernoulli(12, algorithm='bernmm')
288
-691/2730
289
sage: bernoulli(12, algorithm='bernmm', num_threads=4)
290
-691/2730
291
292
TESTS::
293
294
sage: algs = ['gap','gp','pari','bernmm']
295
sage: test_list = [ZZ.random_element(2, 2255) for _ in range(500)]
296
sage: vals = [[bernoulli(i,algorithm = j) for j in algs] for i in test_list] # long time (up to 21s on sage.math, 2011)
297
sage: union([len(union(x))==1 for x in vals]) # long time (depends on previous line)
298
[True]
299
sage: algs = ['gp','pari','bernmm']
300
sage: test_list = [ZZ.random_element(2256, 5000) for _ in range(500)]
301
sage: vals = [[bernoulli(i,algorithm = j) for j in algs] for i in test_list] # long time (up to 30s on sage.math, 2011)
302
sage: union([len(union(x))==1 for x in vals]) # long time (depends on previous line)
303
[True]
304
305
AUTHOR:
306
307
- David Joyner and William Stein
308
"""
309
from sage.rings.all import Integer, Rational
310
n = Integer(n)
311
312
if algorithm == 'default':
313
algorithm = 'pari' if n <= 30000 else 'bernmm'
314
315
if algorithm == 'pari':
316
x = pari(n).bernfrac() # Use the PARI C library
317
return Rational(x)
318
elif algorithm == 'gap':
319
import sage.interfaces.gap
320
x = sage.interfaces.gap.gap('Bernoulli(%s)'%n)
321
return Rational(x)
322
elif algorithm == 'magma':
323
import sage.interfaces.magma
324
x = sage.interfaces.magma.magma('Bernoulli(%s)'%n)
325
return Rational(x)
326
elif algorithm == 'gp':
327
import sage.interfaces.gp
328
x = sage.interfaces.gp.gp('bernfrac(%s)'%n)
329
return Rational(x)
330
elif algorithm == 'bernmm':
331
import sage.rings.bernmm
332
return sage.rings.bernmm.bernmm_bern_rat(n, num_threads)
333
else:
334
raise ValueError, "invalid choice of algorithm"
335
336
337
def factorial(n, algorithm='gmp'):
338
r"""
339
Compute the factorial of `n`, which is the product
340
`1\cdot 2\cdot 3 \cdots (n-1)\cdot n`.
341
342
INPUT:
343
344
- ``n`` - an integer
345
346
- ``algorithm`` - string (default: 'gmp'):
347
348
- ``'gmp'`` - use the GMP C-library factorial function
349
350
- ``'pari'`` - use PARI's factorial function
351
352
OUTPUT: an integer
353
354
EXAMPLES::
355
356
sage: from sage.rings.arith import factorial
357
sage: factorial(0)
358
1
359
sage: factorial(4)
360
24
361
sage: factorial(10)
362
3628800
363
sage: factorial(1) == factorial(0)
364
True
365
sage: factorial(6) == 6*5*4*3*2
366
True
367
sage: factorial(1) == factorial(0)
368
True
369
sage: factorial(71) == 71* factorial(70)
370
True
371
sage: factorial(-32)
372
Traceback (most recent call last):
373
...
374
ValueError: factorial -- must be nonnegative
375
376
PERFORMANCE: This discussion is valid as of April 2006. All timings
377
below are on a Pentium Core Duo 2Ghz MacBook Pro running Linux with
378
a 2.6.16.1 kernel.
379
380
381
- It takes less than a minute to compute the factorial of
382
`10^7` using the GMP algorithm, and the factorial of
383
`10^6` takes less than 4 seconds.
384
385
- The GMP algorithm is faster and more memory efficient than the
386
PARI algorithm. E.g., PARI computes `10^7` factorial in 100
387
seconds on the core duo 2Ghz.
388
389
- For comparison, computation in Magma `\leq` 2.12-10 of
390
`n!` is best done using ``*[1..n]``. It takes
391
113 seconds to compute the factorial of `10^7` and 6
392
seconds to compute the factorial of `10^6`. Mathematica
393
V5.2 compute the factorial of `10^7` in 136 seconds and the
394
factorial of `10^6` in 7 seconds. (Mathematica is notably
395
very efficient at memory usage when doing factorial
396
calculations.)
397
"""
398
if n < 0:
399
raise ValueError, "factorial -- must be nonnegative"
400
if algorithm == 'gmp':
401
return ZZ(n).factorial()
402
elif algorithm == 'pari':
403
return pari.factorial(n)
404
else:
405
raise ValueError, 'unknown algorithm'
406
407
def is_prime(n):
408
r"""
409
Returns ``True`` if `n` is prime, and ``False`` otherwise.
410
411
AUTHORS:
412
413
- Kevin Stueve [email protected] (2010-01-17):
414
delegated calculation to ``n.is_prime()``
415
416
INPUT:
417
418
- ``n`` - the object for which to determine primality
419
420
OUTPUT:
421
422
- ``bool`` - ``True`` or ``False``
423
424
EXAMPLES::
425
426
sage: is_prime(389)
427
True
428
sage: is_prime(2000)
429
False
430
sage: is_prime(2)
431
True
432
sage: is_prime(-1)
433
False
434
sage: factor(-6)
435
-1 * 2 * 3
436
sage: is_prime(1)
437
False
438
sage: is_prime(-2)
439
False
440
441
ALGORITHM:
442
443
Calculation is delegated to the ``n.is_prime()`` method, or in special
444
cases (e.g., Python ``int``s) to ``Integer(n).is_prime()``. If an
445
``n.is_prime()`` method is not available, it otherwise raises a
446
``TypeError``.
447
"""
448
if isinstance(n, sage.symbolic.expression.Expression):
449
try:
450
n = n.pyobject()
451
except TypeError:
452
pass
453
454
from sage.structure.proof.all import arithmetic
455
proof = arithmetic()
456
if isinstance(n, int) or isinstance(n, long):
457
from sage.rings.integer import Integer
458
if proof:
459
return Integer(n).is_prime()
460
else:
461
return Integer(n).is_pseudoprime()
462
try:
463
if proof:
464
return n.is_prime()
465
else:
466
return n.is_pseudoprime()
467
except AttributeError:
468
raise TypeError, "is_prime() is not written for this type"
469
470
def is_pseudoprime(n, flag=0):
471
r"""
472
Returns True if `x` is a pseudo-prime, and False otherwise. The
473
result is *NOT* proven correct - *this is a pseudo-primality
474
test!*.
475
476
INPUT:
477
478
- ``flag`` - int
479
- ``0`` (default): checks whether x is a Baillie-Pomerance-
480
Selfridge-Wagstaff pseudo prime (strong Rabin-Miller pseudo
481
prime for base 2, followed by strong Lucas test for the
482
sequence (P,-1), P smallest positive integer such that `P^2
483
- 4` is not a square mod x).
484
- ``>0``: checks whether x is a strong Miller-Rabin pseudo
485
prime for flag randomly chosen bases (with end-matching to
486
catch square roots of -1).
487
488
OUTPUT:
489
490
- ``bool`` - True or False
491
492
.. note::
493
494
We do not consider negatives of prime numbers as prime.
495
496
EXAMPLES::
497
498
sage: is_pseudoprime(389)
499
True
500
sage: is_pseudoprime(2000)
501
False
502
sage: is_pseudoprime(2)
503
True
504
sage: is_pseudoprime(-1)
505
False
506
sage: factor(-6)
507
-1 * 2 * 3
508
sage: is_pseudoprime(1)
509
False
510
sage: is_pseudoprime(-2)
511
False
512
513
IMPLEMENTATION: Calls the PARI ispseudoprime function.
514
"""
515
n = ZZ(n)
516
return pari(n).ispseudoprime()
517
518
def is_prime_power(n, flag=0):
519
r"""
520
Returns True if `n` is a prime power, and False otherwise. The
521
result is proven correct - *this is NOT a pseudo-primality test!*.
522
523
INPUT:
524
525
- ``n`` - an integer or rational number
526
- ``flag (for primality testing)`` - int
527
- ``0`` (default): use a combination of algorithms.
528
- ``1``: certify primality using the Pocklington-Lehmer Test.
529
- ``2``: certify primality using the APRCL test.
530
531
532
EXAMPLES::
533
534
sage: is_prime_power(389)
535
True
536
sage: is_prime_power(2000)
537
False
538
sage: is_prime_power(2)
539
True
540
sage: is_prime_power(1024)
541
True
542
sage: is_prime_power(-1)
543
False
544
sage: is_prime_power(1)
545
True
546
sage: is_prime_power(997^100)
547
True
548
sage: is_prime_power(1/2197)
549
True
550
sage: is_prime_power(1/100)
551
False
552
sage: is_prime_power(2/5)
553
False
554
"""
555
try:
556
n = ZZ(n)
557
except TypeError:
558
# n might be a nonintegral rational number, in which case it is a
559
# prime power iff the integer 1/n is a prime power
560
r = QQ(1/n)
561
if not r.is_integral():
562
return False
563
n = ZZ(r)
564
565
from sage.structure.proof.all import arithmetic
566
proof = arithmetic()
567
if proof:
568
return n.is_prime_power(flag=flag)
569
else:
570
return is_pseudoprime_small_power(n)
571
572
def is_pseudoprime_small_power(n, bound=1024, get_data=False):
573
r"""
574
Return True if `n` is a small power of a pseudoprime, and False
575
otherwise. The result is *NOT* proven correct - *this IS a
576
pseudo-primality test!*.
577
578
If `get_data` is set to true and `n = p^d`, for a pseudoprime `p`
579
and power `d`, return [(p, d)].
580
581
582
INPUT:
583
584
- ``n`` - an integer
585
- ``bound (default: 1024)`` - int: highest power to test.
586
- ``get_data`` - boolean: return small pseudoprime and the power.
587
588
EXAMPLES::
589
590
sage: is_pseudoprime_small_power(389)
591
True
592
sage: is_pseudoprime_small_power(2000)
593
False
594
sage: is_pseudoprime_small_power(2)
595
True
596
sage: is_pseudoprime_small_power(1024)
597
True
598
sage: is_pseudoprime_small_power(-1)
599
False
600
sage: is_pseudoprime_small_power(1)
601
True
602
sage: is_pseudoprime_small_power(997^100)
603
True
604
605
The default bound is 1024::
606
607
sage: is_pseudoprime_small_power(3^1024)
608
True
609
sage: is_pseudoprime_small_power(3^1025)
610
False
611
612
But it can be set higher or lower::
613
614
sage: is_pseudoprime_small_power(3^1025, bound=2000)
615
True
616
sage: is_pseudoprime_small_power(3^100, bound=20)
617
False
618
619
Use of the get_data keyword::
620
621
sage: is_pseudoprime_small_power(3^1024, get_data=True)
622
[(3, 1024)]
623
sage: is_pseudoprime_small_power(2^256, get_data=True)
624
[(2, 256)]
625
sage: is_pseudoprime_small_power(31, get_data=True)
626
[(31, 1)]
627
sage: is_pseudoprime_small_power(15, get_data=True)
628
False
629
"""
630
n = ZZ(n)
631
if n == 1:
632
# canonical way to write 1 as a prime power?
633
return True
634
if n <= 0:
635
return False
636
if n.is_pseudoprime():
637
if get_data == True:
638
return [(n, 1)]
639
else:
640
return True
641
for i in xrange(2, bound + 1):
642
p, boo = n.nth_root(i, truncate_mode=True)
643
if boo:
644
if p.is_pseudoprime():
645
if get_data == True:
646
return [(p, i)]
647
else:
648
return True
649
return False
650
651
652
def valuation(m,*args1, **args2):
653
"""
654
This actually just calls the m.valuation() method.
655
See the documentation of m.valuation() for a more precise description.
656
Use of this function by developers is discouraged. Use m.valuation() instead.
657
658
.. NOTE::
659
660
This is not always a valuation in the mathematical sense.
661
For more information see:
662
sage.rings.finite_rings.integer_mod.IntegerMod_int.valuation
663
664
EXAMPLES::
665
666
sage: valuation(512,2)
667
9
668
sage: valuation(1,2)
669
0
670
sage: valuation(5/9, 3)
671
-2
672
673
Valuation of 0 is defined, but valuation with respect to 0 is not::
674
675
sage: valuation(0,7)
676
+Infinity
677
sage: valuation(3,0)
678
Traceback (most recent call last):
679
...
680
ValueError: You can only compute the valuation with respect to a integer larger than 1.
681
682
Here are some other examples::
683
684
sage: valuation(100,10)
685
2
686
sage: valuation(200,10)
687
2
688
sage: valuation(243,3)
689
5
690
sage: valuation(243*10007,3)
691
5
692
sage: valuation(243*10007,10007)
693
1
694
sage: y = QQ['y'].gen()
695
sage: valuation(y^3, y)
696
3
697
sage: x = QQ[['x']].gen()
698
sage: valuation((x^3-x^2)/(x-4))
699
2
700
sage: valuation(4r,2r)
701
2
702
sage: valuation(1r,1r)
703
Traceback (most recent call last):
704
...
705
ValueError: You can only compute the valuation with respect to a integer larger than 1.
706
"""
707
if isinstance(m,(int,long)):
708
m=ZZ(m)
709
return m.valuation(*args1, **args2)
710
711
def prime_powers(start, stop=None):
712
r"""
713
List of all positive primes powers between ``start`` and
714
``stop``-1, inclusive. If the second argument is omitted, returns
715
the prime powers up to the first argument.
716
717
INPUT:
718
719
- ``start`` - an integer. If two inputs are given, a lower bound
720
for the returned set of prime powers. If this is the only input,
721
then it is an upper bound.
722
723
- ``stop`` - an integer (default: ``None``) An upper bound for the
724
returned set of prime powers.
725
726
OUTPUT:
727
728
The set of all prime powers between ``start`` and ``stop`` or, if
729
only one argument is passed, the set of all prime powers between 1
730
and ``start``. Note that we will here say that the number `n` is a
731
prime power if `n=p^k`, where `p` is a prime number and `k` is a
732
nonnegative integer. Thus, `1` is a prime power, as `1 = 2^0`.
733
734
EXAMPLES::
735
736
sage: prime_powers(20)
737
[1, 2, 3, 4, 5, 7, 8, 9, 11, 13, 16, 17, 19]
738
sage: len(prime_powers(1000))
739
194
740
sage: len(prime_range(1000))
741
168
742
sage: a = [z for z in range(95,1234) if is_prime_power(z)]
743
sage: b = prime_powers(95,1234)
744
sage: len(b)
745
194
746
sage: len(a)
747
194
748
sage: a[:10]
749
[97, 101, 103, 107, 109, 113, 121, 125, 127, 128]
750
sage: b[:10]
751
[97, 101, 103, 107, 109, 113, 121, 125, 127, 128]
752
sage: a == b
753
True
754
sage: prime_powers(10,7)
755
[]
756
sage: prime_powers(-5)
757
[]
758
sage: prime_powers(-1,2)
759
[1]
760
761
TESTS::
762
763
sage: v = prime_powers(10)
764
sage: type(v[0]) # trac #922
765
<type 'sage.rings.integer.Integer'>
766
767
sage: prime_powers("foo")
768
Traceback (most recent call last):
769
...
770
TypeError: start must be an integer, foo is not an integer
771
772
sage: prime_powers(6, "bar")
773
Traceback (most recent call last):
774
...
775
TypeError: stop must be an integer, bar is not an integer
776
777
"""
778
from sage.rings.integer import Integer
779
# check to ensure that both inputs are positive integers
780
if not isinstance(start, (int, Integer)):
781
raise TypeError("start must be an integer, {} is not an integer".format(start))
782
if not (isinstance(stop, (int, Integer)) or stop is None):
783
raise TypeError("stop must be an integer, {} is not an integer".format(stop))
784
785
# coerce inputs that are ints into Integers for efficiency
786
start = Integer(start)
787
if(stop is not None):
788
stop = Integer(stop)
789
790
# deal with the case in which only one input is given
791
if stop is None:
792
start, stop = 1, Integer(start)
793
794
# inserted to prevent an error from occurring
795
if stop < 1:
796
return [];
797
798
# find all the primes in the given range
799
from fast_arith import prime_range
800
temp = prime_range(stop)
801
output = [p for p in temp if p>=start]
802
803
if start <= 1:
804
output.append(Integer(1))
805
806
s = stop.sqrt()
807
for p in temp:
808
# if p > the square root of stop, p^2 will be outside the given
809
# range
810
if p > s:
811
break
812
q = p*p
813
# check if each power of p falls within the given range
814
while q < stop:
815
if start <= q:
816
output.append(q)
817
q *= p
818
819
output.sort()
820
return output
821
822
def primes_first_n(n, leave_pari=False):
823
r"""
824
Return the first `n` primes.
825
826
INPUT:
827
828
- `n` - a nonnegative integer
829
830
OUTPUT:
831
832
- a list of the first `n` prime numbers.
833
834
EXAMPLES::
835
836
sage: primes_first_n(10)
837
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
838
sage: len(primes_first_n(1000))
839
1000
840
sage: primes_first_n(0)
841
[]
842
"""
843
if n < 0:
844
raise ValueError, "n must be nonnegative"
845
if n < 1:
846
return []
847
return fast_arith.prime_range(pari.nth_prime(n) + 1)
848
849
#
850
# This is from
851
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/366178
852
# It's impressively fast given that it's in Pure Python.
853
#
854
def eratosthenes(n):
855
r"""
856
Return a list of the primes `\leq n`.
857
858
This is extremely slow and is for educational purposes only.
859
860
INPUT:
861
862
- ``n`` - a positive integer
863
864
OUTPUT:
865
866
- a list of primes less than or equal to n.
867
868
869
EXAMPLES::
870
871
sage: len(eratosthenes(100))
872
25
873
sage: eratosthenes(3)
874
[2, 3]
875
"""
876
n = int(n)
877
if n == 2:
878
return [2]
879
elif n<2:
880
return []
881
s = range(3,n+3,2)
882
mroot = n ** 0.5
883
half = (n+1)/2
884
i = 0
885
m = 3
886
while m <= mroot:
887
if s[i]:
888
j = (m*m-3)/2
889
s[j] = 0
890
while j < half:
891
s[j] = 0
892
j += m
893
i = i+1
894
m = 2*i+3
895
return [ZZ(2)] + [ZZ(x) for x in s if x and x <= n]
896
897
# My old versions; not as fast as the above.
898
## def eratosthenes(n):
899
## """
900
## Returns a list of the primes up to n, computed
901
## using the Sieve of Eratosthenes.
902
## Input:
903
## n -- a positive integer
904
## Output:
905
## list -- a list of the primes up to n
906
## Examples:
907
## sage: eratosthenes(7)
908
## [2, 3, 5, 7]
909
## sage: eratosthenes(45)
910
## [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43]
911
## """
912
## if n <= 1: return []
913
## X = [i for i in range(3,n+1) if i%2 != 0]
914
## P = [2]
915
## sqrt_n = sqrt(n)
916
## while len(X) > 0 and X[0] <= sqrt_n:
917
## p = X[0]
918
## P.append(p)
919
## X = [a for a in X if a%p != 0]
920
## return P + X
921
922
def primes(start, stop=None, proof=None):
923
r"""
924
Returns an iterator over all primes between start and stop-1,
925
inclusive. This is much slower than ``prime_range``, but
926
potentially uses less memory. As with :func:`next_prime`, the optional
927
argument proof controls whether the numbers returned are
928
guaranteed to be prime or not.
929
930
This command is like the xrange command, except it only iterates
931
over primes. In some cases it is better to use primes than
932
``prime_range``, because primes does not build a list of all primes in
933
the range in memory all at once. However, it is potentially much
934
slower since it simply calls the :func:`next_prime` function
935
repeatedly, and :func:`next_prime` is slow.
936
937
INPUT:
938
939
- ``start`` - an integer - lower bound for the primes
940
941
- ``stop`` - an integer (or infinity) optional argument -
942
giving upper (open) bound for the primes
943
944
- ``proof`` - bool or None (default: None) If True, the function
945
yields only proven primes. If False, the function uses a
946
pseudo-primality test, which is much faster for really big
947
numbers but does not provide a proof of primality. If None,
948
uses the global default (see :mod:`sage.structure.proof.proof`)
949
950
OUTPUT:
951
952
- an iterator over primes from start to stop-1, inclusive
953
954
955
EXAMPLES::
956
957
sage: for p in primes(5,10):
958
... print p
959
...
960
5
961
7
962
sage: list(primes(13))
963
[2, 3, 5, 7, 11]
964
sage: list(primes(10000000000, 10000000100))
965
[10000000019, 10000000033, 10000000061, 10000000069, 10000000097]
966
sage: max(primes(10^100, 10^100+10^4, proof=False))
967
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000009631
968
sage: next(p for p in primes(10^20, infinity) if is_prime(2*p+1))
969
100000000000000001243
970
971
972
TESTS::
973
974
sage: for a in range(-10, 50):
975
... for b in range(-10, 50):
976
... assert list(primes(a,b)) == list(filter(is_prime, xrange(a,b)))
977
...
978
sage: sum(primes(-10, 9973, proof=False)) == sum(filter(is_prime, range(-10, 9973)))
979
True
980
sage: for p in primes(10, infinity):
981
... if p > 20: break
982
... print p
983
...
984
11
985
13
986
17
987
19
988
sage: next(p for p in primes(10,oo)) # checks alternate infinity notation
989
11
990
"""
991
from sage.rings.infinity import infinity
992
993
start = ZZ(start)
994
if stop == None:
995
stop = start
996
start = ZZ(2)
997
elif stop != infinity:
998
stop = ZZ(stop)
999
n = start - 1
1000
while True:
1001
n = next_prime(n, proof)
1002
if n < stop:
1003
yield n
1004
else:
1005
return
1006
1007
def next_prime_power(n):
1008
"""
1009
The next prime power greater than the integer n. If n is a prime
1010
power, then this function does not return n, but the next prime
1011
power after n.
1012
1013
EXAMPLES::
1014
1015
sage: next_prime_power(-10)
1016
1
1017
sage: is_prime_power(1)
1018
True
1019
sage: next_prime_power(0)
1020
1
1021
sage: next_prime_power(1)
1022
2
1023
sage: next_prime_power(2)
1024
3
1025
sage: next_prime_power(10)
1026
11
1027
sage: next_prime_power(7)
1028
8
1029
sage: next_prime_power(99)
1030
101
1031
"""
1032
if n < 0: # negatives are not prime.
1033
return ZZ(1)
1034
if n == 2:
1035
return ZZ(3)
1036
n = ZZ(n) + 1
1037
while not is_prime_power(n): # pari isprime is provably correct
1038
n += 1
1039
return n
1040
1041
def next_probable_prime(n):
1042
"""
1043
Returns the next probable prime after self, as determined by PARI.
1044
1045
INPUT:
1046
1047
1048
- ``n`` - an integer
1049
1050
1051
EXAMPLES::
1052
1053
sage: next_probable_prime(-100)
1054
2
1055
sage: next_probable_prime(19)
1056
23
1057
sage: next_probable_prime(int(999999999))
1058
1000000007
1059
sage: next_probable_prime(2^768)
1060
1552518092300708935148979488462502555256886017116696611139052038026050952686376886330878408828646477950487730697131073206171580044114814391444287275041181139204454976020849905550265285631598444825262999193716468750892846853816058039
1061
"""
1062
return ZZ(n).next_probable_prime()
1063
1064
def next_prime(n, proof=None):
1065
"""
1066
The next prime greater than the integer n. If n is prime, then this
1067
function does not return n, but the next prime after n. If the
1068
optional argument proof is False, this function only returns a
1069
pseudo-prime, as defined by the PARI nextprime function. If it is
1070
None, uses the global default (see :mod:`sage.structure.proof.proof`)
1071
1072
INPUT:
1073
1074
1075
- ``n`` - integer
1076
1077
- ``proof`` - bool or None (default: None)
1078
1079
1080
EXAMPLES::
1081
1082
sage: next_prime(-100)
1083
2
1084
sage: next_prime(1)
1085
2
1086
sage: next_prime(2)
1087
3
1088
sage: next_prime(3)
1089
5
1090
sage: next_prime(4)
1091
5
1092
1093
Notice that the next_prime(5) is not 5 but 7.
1094
1095
::
1096
1097
sage: next_prime(5)
1098
7
1099
sage: next_prime(2004)
1100
2011
1101
"""
1102
try:
1103
return n.next_prime(proof)
1104
except AttributeError:
1105
return ZZ(n).next_prime(proof)
1106
1107
def previous_prime(n):
1108
"""
1109
The largest prime < n. The result is provably correct. If n <= 1,
1110
this function raises a ValueError.
1111
1112
EXAMPLES::
1113
1114
sage: previous_prime(10)
1115
7
1116
sage: previous_prime(7)
1117
5
1118
sage: previous_prime(8)
1119
7
1120
sage: previous_prime(7)
1121
5
1122
sage: previous_prime(5)
1123
3
1124
sage: previous_prime(3)
1125
2
1126
sage: previous_prime(2)
1127
Traceback (most recent call last):
1128
...
1129
ValueError: no previous prime
1130
sage: previous_prime(1)
1131
Traceback (most recent call last):
1132
...
1133
ValueError: no previous prime
1134
sage: previous_prime(-20)
1135
Traceback (most recent call last):
1136
...
1137
ValueError: no previous prime
1138
"""
1139
n = ZZ(n)-1
1140
if n <= 1:
1141
raise ValueError, "no previous prime"
1142
if n <= 3:
1143
return ZZ(n)
1144
if n%2 == 0:
1145
n -= 1
1146
while not is_prime(n):
1147
n -= 2
1148
return ZZ(n)
1149
1150
def previous_prime_power(n):
1151
r"""
1152
The largest prime power `< n`. The result is provably
1153
correct. If `n \leq 2`, this function returns `-x`,
1154
where `x` is prime power and `-x < n` and no larger
1155
negative of a prime power has this property.
1156
1157
EXAMPLES::
1158
1159
sage: previous_prime_power(2)
1160
1
1161
sage: previous_prime_power(10)
1162
9
1163
sage: previous_prime_power(7)
1164
5
1165
sage: previous_prime_power(127)
1166
125
1167
1168
::
1169
1170
sage: previous_prime_power(0)
1171
Traceback (most recent call last):
1172
...
1173
ValueError: no previous prime power
1174
sage: previous_prime_power(1)
1175
Traceback (most recent call last):
1176
...
1177
ValueError: no previous prime power
1178
1179
::
1180
1181
sage: n = previous_prime_power(2^16 - 1)
1182
sage: while is_prime(n):
1183
... n = previous_prime_power(n)
1184
sage: factor(n)
1185
251^2
1186
"""
1187
n = ZZ(n)-1
1188
if n <= 0:
1189
raise ValueError, "no previous prime power"
1190
while not is_prime_power(n):
1191
n -= 1
1192
return n
1193
1194
def random_prime(n, proof=None, lbound=2):
1195
"""
1196
Returns a random prime p between `lbound` and n (i.e. `lbound <= p <= n`).
1197
The returned prime is chosen uniformly at random from the set of prime
1198
numbers less than or equal to n.
1199
1200
INPUT:
1201
1202
- ``n`` - an integer >= 2.
1203
1204
- ``proof`` - bool or None (default: None) If False, the function uses a
1205
pseudo-primality test, which is much faster for really big numbers but
1206
does not provide a proof of primality. If None, uses the global default
1207
(see :mod:`sage.structure.proof.proof`)
1208
1209
- ``lbound`` - an integer >= 2
1210
lower bound for the chosen primes
1211
1212
EXAMPLES::
1213
1214
sage: random_prime(100000)
1215
88237
1216
sage: random_prime(2)
1217
2
1218
1219
Here we generate a random prime between 100 and 200::
1220
1221
sage: random_prime(200, lbound=100)
1222
149
1223
1224
If all we care about is finding a pseudo prime, then we can pass
1225
in ``proof=False`` ::
1226
1227
sage: random_prime(200, proof=False, lbound=100)
1228
149
1229
1230
TESTS::
1231
1232
sage: type(random_prime(2))
1233
<type 'sage.rings.integer.Integer'>
1234
sage: type(random_prime(100))
1235
<type 'sage.rings.integer.Integer'>
1236
sage: random_prime(1, lbound=-2) #caused Sage hang #10112
1237
Traceback (most recent call last):
1238
...
1239
ValueError: n must be greater than or equal to 2
1240
sage: random_prime(126, lbound=114)
1241
Traceback (most recent call last):
1242
...
1243
ValueError: There are no primes between 114 and 126 (inclusive)
1244
1245
1246
AUTHORS:
1247
1248
- Jon Hanke (2006-08-08): with standard Stein cleanup
1249
1250
- Jonathan Bober (2007-03-17)
1251
"""
1252
# since we don't want current_randstate to get
1253
# pulled when you say "from sage.arith import *".
1254
from sage.misc.randstate import current_randstate
1255
from sage.structure.proof.proof import get_flag
1256
proof = get_flag(proof, "arithmetic")
1257
n = ZZ(n)
1258
if n < 2:
1259
raise ValueError, "n must be greater than or equal to 2"
1260
if n < lbound:
1261
raise ValueError, "n must be at least lbound: %s"%(lbound)
1262
elif n == 2:
1263
return n
1264
lbound = max(2, lbound)
1265
if lbound > 2:
1266
if lbound == 3 or n <= 2*lbound - 2:
1267
# check for Betrand's postulate (proved by Chebyshev)
1268
if lbound < 25 or n <= 6*lbound/5:
1269
# see J. Nagura, Proc. Japan Acad. 28, (1952). 177-181.
1270
if lbound < 2010760 or n <= 16598*lbound/16597:
1271
# see L. Schoenfeld, Math. Comp. 30 (1976), no. 134, 337-360.
1272
if proof:
1273
smallest_prime = ZZ(lbound-1).next_prime()
1274
else:
1275
smallest_prime = ZZ(lbound-1).next_probable_prime()
1276
if smallest_prime > n:
1277
raise ValueError, \
1278
"There are no primes between %s and %s (inclusive)" % (lbound, n)
1279
1280
if proof:
1281
prime_test = is_prime
1282
else:
1283
prime_test = is_pseudoprime
1284
randint = current_randstate().python_random().randint
1285
while True:
1286
# In order to ensure that the returned prime is chosen
1287
# uniformly from the set of primes it is necessary to
1288
# choose a random number and then test for primality.
1289
# The method of choosing a random number and then returning
1290
# the closest prime smaller than it would typically not,
1291
# for example, return the first of a pair of twin primes.
1292
p = randint(lbound, n)
1293
if prime_test(p):
1294
return ZZ(p)
1295
1296
1297
def divisors(n):
1298
"""
1299
Returns a list of all positive integer divisors of the nonzero
1300
integer n.
1301
1302
INPUT:
1303
1304
1305
- ``n`` - the element
1306
1307
1308
EXAMPLES::
1309
1310
sage: divisors(-3)
1311
[1, 3]
1312
sage: divisors(6)
1313
[1, 2, 3, 6]
1314
sage: divisors(28)
1315
[1, 2, 4, 7, 14, 28]
1316
sage: divisors(2^5)
1317
[1, 2, 4, 8, 16, 32]
1318
sage: divisors(100)
1319
[1, 2, 4, 5, 10, 20, 25, 50, 100]
1320
sage: divisors(1)
1321
[1]
1322
sage: divisors(0)
1323
Traceback (most recent call last):
1324
...
1325
ValueError: n must be nonzero
1326
sage: divisors(2^3 * 3^2 * 17)
1327
[1, 2, 3, 4, 6, 8, 9, 12, 17, 18, 24, 34, 36, 51, 68, 72, 102, 136, 153, 204, 306, 408, 612, 1224]
1328
1329
This function works whenever one has unique factorization::
1330
1331
sage: K.<a> = QuadraticField(7)
1332
sage: divisors(K.ideal(7))
1333
[Fractional ideal (1), Fractional ideal (a), Fractional ideal (7)]
1334
sage: divisors(K.ideal(3))
1335
[Fractional ideal (1), Fractional ideal (3), Fractional ideal (-a + 2), Fractional ideal (-a - 2)]
1336
sage: divisors(K.ideal(35))
1337
[Fractional ideal (1), Fractional ideal (35), Fractional ideal (5*a), Fractional ideal (5), Fractional ideal (a), Fractional ideal (7)]
1338
1339
TESTS::
1340
1341
sage: divisors(int(300))
1342
[1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 25, 30, 50, 60, 75, 100, 150, 300]
1343
"""
1344
if not n:
1345
raise ValueError, "n must be nonzero"
1346
1347
R = parent(n)
1348
if R in [int, long]:
1349
n = ZZ(n) # we have specialized code for this case, make sure it gets used
1350
try:
1351
return n.divisors()
1352
except AttributeError:
1353
pass
1354
f = factor(n)
1355
one = R(1)
1356
all = [one]
1357
for p, e in f:
1358
prev = all[:]
1359
pn = one
1360
for i in range(e):
1361
pn *= p
1362
all.extend([a*pn for a in prev])
1363
all.sort()
1364
return all
1365
1366
class Sigma:
1367
"""
1368
Return the sum of the k-th powers of the divisors of n.
1369
1370
INPUT:
1371
1372
1373
- ``n`` - integer
1374
1375
- ``k`` - integer (default: 1)
1376
1377
1378
OUTPUT: integer
1379
1380
EXAMPLES::
1381
1382
sage: sigma(5)
1383
6
1384
sage: sigma(5,2)
1385
26
1386
1387
The sigma function also has a special plotting method.
1388
1389
::
1390
1391
sage: P = plot(sigma, 1, 100)
1392
1393
This method also works with k-th powers.
1394
1395
::
1396
1397
sage: P = plot(sigma, 1, 100, k=2)
1398
1399
AUTHORS:
1400
1401
- William Stein: original implementation
1402
1403
- Craig Citro (2007-06-01): rewrote for huge speedup
1404
1405
TESTS::
1406
1407
sage: sigma(100,4)
1408
106811523
1409
sage: sigma(factorial(100),3).mod(144169)
1410
3672
1411
sage: sigma(factorial(150),12).mod(691)
1412
176
1413
sage: RR(sigma(factorial(133),20))
1414
2.80414775675747e4523
1415
sage: sigma(factorial(100),0)
1416
39001250856960000
1417
sage: sigma(factorial(41),1)
1418
229199532273029988767733858700732906511758707916800
1419
"""
1420
def __repr__(self):
1421
"""
1422
A description of this class, which computes the sum of the
1423
k-th powers of the divisors of n.
1424
1425
EXAMPLES::
1426
1427
sage: Sigma().__repr__()
1428
'Function that adds up (k-th powers of) the divisors of n'
1429
"""
1430
return "Function that adds up (k-th powers of) the divisors of n"
1431
1432
def __call__(self, n, k=1):
1433
"""
1434
Computes the sum of (the k-th powers of) the divisors of n.
1435
1436
EXAMPLES::
1437
1438
sage: q = Sigma()
1439
sage: q(10)
1440
18
1441
sage: q(10,2)
1442
130
1443
"""
1444
n = ZZ(n)
1445
k = ZZ(k)
1446
one = ZZ(1)
1447
1448
if (k == ZZ(0)):
1449
return prod([ expt+one for p, expt in factor(n) ])
1450
elif (k == one):
1451
return prod([ (p**(expt+one) - one).divide_knowing_divisible_by(p - one)
1452
for p, expt in factor(n) ])
1453
else:
1454
return prod([ (p**((expt+one)*k)-one).divide_knowing_divisible_by(p**k-one)
1455
for p,expt in factor(n) ])
1456
1457
def plot(self, xmin=1, xmax=50, k=1, pointsize=30, rgbcolor=(0,0,1), join=True,
1458
**kwds):
1459
"""
1460
Plot the sigma (sum of k-th powers of divisors) function.
1461
1462
INPUT:
1463
1464
1465
- ``xmin`` - default: 1
1466
1467
- ``xmax`` - default: 50
1468
1469
- ``k`` - default: 1
1470
1471
- ``pointsize`` - default: 30
1472
1473
- ``rgbcolor`` - default: (0,0,1)
1474
1475
- ``join`` - default: True; whether to join the
1476
points.
1477
1478
- ``**kwds`` - passed on
1479
1480
EXAMPLES::
1481
1482
sage: p = Sigma().plot()
1483
sage: p.ymax()
1484
124.0
1485
"""
1486
v = [(n,sigma(n,k)) for n in range(xmin,xmax + 1)]
1487
from sage.plot.all import list_plot
1488
P = list_plot(v, pointsize=pointsize, rgbcolor=rgbcolor, **kwds)
1489
if join:
1490
P += list_plot(v, plotjoined=True, rgbcolor=(0.7,0.7,0.7), **kwds)
1491
return P
1492
1493
sigma = Sigma()
1494
1495
def gcd(a, b=None, **kwargs):
1496
r"""
1497
The greatest common divisor of a and b, or if a is a list and b is
1498
omitted the greatest common divisor of all elements of a.
1499
1500
INPUT:
1501
1502
1503
- ``a,b`` - two elements of a ring with gcd or
1504
1505
- ``a`` - a list or tuple of elements of a ring with
1506
gcd
1507
1508
1509
Additional keyword arguments are passed to the respectively called
1510
methods.
1511
1512
OUTPUT:
1513
1514
The given elements are first coerced into a common parent. Then,
1515
their greatest common divisor *in that common parent* is returned.
1516
1517
EXAMPLES::
1518
1519
sage: GCD(97,100)
1520
1
1521
sage: GCD(97*10^15, 19^20*97^2)
1522
97
1523
sage: GCD(2/3, 4/5)
1524
2/15
1525
sage: GCD([2,4,6,8])
1526
2
1527
sage: GCD(srange(0,10000,10)) # fast !!
1528
10
1529
1530
Note that to take the gcd of `n` elements for `n \not= 2` you must
1531
put the elements into a list by enclosing them in ``[..]``. Before
1532
#4988 the following wrongly returned 3 since the third parameter
1533
was just ignored::
1534
1535
sage: gcd(3,6,2)
1536
Traceback (most recent call last):
1537
...
1538
TypeError: gcd() takes at most 2 arguments (3 given)
1539
sage: gcd([3,6,2])
1540
1
1541
1542
Similarly, giving just one element (which is not a list) gives an error::
1543
1544
sage: gcd(3)
1545
Traceback (most recent call last):
1546
...
1547
TypeError: 'sage.rings.integer.Integer' object is not iterable
1548
1549
By convention, the gcd of the empty list is (the integer) 0::
1550
1551
sage: gcd([])
1552
0
1553
sage: type(gcd([]))
1554
<type 'sage.rings.integer.Integer'>
1555
1556
TESTS:
1557
1558
The following shows that indeed coercion takes place before computing
1559
the gcd. This behaviour was introduced in trac ticket #10771::
1560
1561
sage: R.<x>=QQ[]
1562
sage: S.<x>=ZZ[]
1563
sage: p = S.random_element()
1564
sage: q = R.random_element()
1565
sage: parent(gcd(1/p,q))
1566
Fraction Field of Univariate Polynomial Ring in x over Rational Field
1567
sage: parent(gcd([1/p,q]))
1568
Fraction Field of Univariate Polynomial Ring in x over Rational Field
1569
1570
Make sure we try QQ and not merely ZZ (:trac:`13014`)::
1571
1572
sage: bool(gcd(2/5, 3/7) == gcd(SR(2/5), SR(3/7)))
1573
True
1574
1575
Make sure that the gcd of Expressions stays symbolic::
1576
1577
sage: parent(gcd(2, 4))
1578
Integer Ring
1579
sage: parent(gcd(SR(2), 4))
1580
Symbolic Ring
1581
sage: parent(gcd(2, SR(4)))
1582
Symbolic Ring
1583
sage: parent(gcd(SR(2), SR(4)))
1584
Symbolic Ring
1585
1586
Verify that objects without gcd methods but which can't be
1587
coerced to ZZ or QQ raise an error::
1588
1589
sage: F.<a,b> = FreeMonoid(2)
1590
sage: gcd(a,b)
1591
Traceback (most recent call last):
1592
...
1593
TypeError: unable to find gcd
1594
1595
"""
1596
# Most common use case first:
1597
if b is not None:
1598
from sage.structure.element import get_coercion_model
1599
cm = get_coercion_model()
1600
a,b = cm.canonical_coercion(a,b)
1601
try:
1602
GCD = a.gcd
1603
except AttributeError:
1604
try:
1605
return ZZ(a).gcd(ZZ(b))
1606
except TypeError:
1607
raise TypeError("unable to find gcd")
1608
return GCD(b, **kwargs)
1609
1610
from sage.structure.sequence import Sequence
1611
seq = Sequence(a)
1612
U = seq.universe()
1613
if U is ZZ or U is int or U is long:# ZZ.has_coerce_map_from(U):
1614
return sage.rings.integer.GCD_list(a)
1615
return __GCD_sequence(seq, **kwargs)
1616
1617
GCD = gcd
1618
1619
def __GCD_sequence(v, **kwargs):
1620
"""
1621
Internal function returning the gcd of the elements of a sequence
1622
1623
INPUT:
1624
1625
1626
- ``v`` - A sequence (possibly empty)
1627
1628
1629
OUTPUT: The gcd of the elements of the sequence as an element of
1630
the sequence's universe, or the integer 0 if the sequence is
1631
empty.
1632
1633
EXAMPLES::
1634
1635
sage: from sage.rings.arith import __GCD_sequence
1636
sage: from sage.structure.sequence import Sequence
1637
sage: l = ()
1638
sage: __GCD_sequence(l)
1639
0
1640
sage: __GCD_sequence(Sequence(srange(10)))
1641
1
1642
sage: X=polygen(QQ)
1643
sage: __GCD_sequence(Sequence((2*X+4,2*X^2,2)))
1644
1
1645
sage: X=polygen(ZZ)
1646
sage: __GCD_sequence(Sequence((2*X+4,2*X^2,2)))
1647
2
1648
"""
1649
if len(v) == 0:
1650
return ZZ(0)
1651
if hasattr(v,'universe'):
1652
g = v.universe()(0)
1653
else:
1654
g = ZZ(0)
1655
one = v.universe()(1)
1656
for vi in v:
1657
g = vi.gcd(g, **kwargs)
1658
if g == one:
1659
return g
1660
return g
1661
1662
def lcm(a, b=None):
1663
"""
1664
The least common multiple of a and b, or if a is a list and b is
1665
omitted the least common multiple of all elements of a.
1666
1667
Note that LCM is an alias for lcm.
1668
1669
INPUT:
1670
1671
1672
- ``a,b`` - two elements of a ring with lcm or
1673
1674
- ``a`` - a list or tuple of elements of a ring with
1675
lcm
1676
1677
OUTPUT:
1678
1679
First, the given elements are coerced into a common parent. Then,
1680
their least common multiple *in that parent* is returned.
1681
1682
EXAMPLES::
1683
1684
sage: lcm(97,100)
1685
9700
1686
sage: LCM(97,100)
1687
9700
1688
sage: LCM(0,2)
1689
0
1690
sage: LCM(-3,-5)
1691
15
1692
sage: LCM([1,2,3,4,5])
1693
60
1694
sage: v = LCM(range(1,10000)) # *very* fast!
1695
sage: len(str(v))
1696
4349
1697
1698
1699
TESTS:
1700
1701
The following tests against a bug that was fixed in trac
1702
ticket #10771::
1703
1704
sage: lcm(4/1,2)
1705
4
1706
1707
The following shows that indeed coercion takes place before
1708
computing the least common multiple::
1709
1710
sage: R.<x>=QQ[]
1711
sage: S.<x>=ZZ[]
1712
sage: p = S.random_element()
1713
sage: q = R.random_element()
1714
sage: parent(lcm([1/p,q]))
1715
Fraction Field of Univariate Polynomial Ring in x over Rational Field
1716
1717
Make sure we try QQ and not merely ZZ (:trac:`13014`)::
1718
1719
sage: bool(lcm(2/5, 3/7) == lcm(SR(2/5), SR(3/7)))
1720
True
1721
1722
Make sure that the lcm of Expressions stays symbolic::
1723
1724
sage: parent(lcm(2, 4))
1725
Integer Ring
1726
sage: parent(lcm(SR(2), 4))
1727
Symbolic Ring
1728
sage: parent(lcm(2, SR(4)))
1729
Symbolic Ring
1730
sage: parent(lcm(SR(2), SR(4)))
1731
Symbolic Ring
1732
1733
Verify that objects without lcm methods but which can't be
1734
coerced to ZZ or QQ raise an error::
1735
1736
sage: F.<a,b> = FreeMonoid(2)
1737
sage: lcm(a,b)
1738
Traceback (most recent call last):
1739
...
1740
TypeError: unable to find lcm
1741
1742
"""
1743
# Most common use case first:
1744
if b is not None:
1745
from sage.structure.element import get_coercion_model
1746
cm = get_coercion_model()
1747
a,b = cm.canonical_coercion(a,b)
1748
try:
1749
LCM = a.lcm
1750
except AttributeError:
1751
try:
1752
return ZZ(a).lcm(ZZ(b))
1753
except TypeError:
1754
raise TypeError("unable to find lcm")
1755
return LCM(b)
1756
1757
from sage.structure.sequence import Sequence
1758
seq = Sequence(a)
1759
U = seq.universe()
1760
if U is ZZ or U is int or U is long:
1761
return sage.rings.integer.LCM_list(a)
1762
return __LCM_sequence(seq)
1763
1764
LCM = lcm
1765
1766
def __LCM_sequence(v):
1767
"""
1768
Internal function returning the lcm of the elements of a sequence
1769
1770
INPUT:
1771
1772
1773
- ``v`` - A sequence (possibly empty)
1774
1775
1776
OUTPUT: The lcm of the elements of the sequence as an element of
1777
the sequence's universe, or the integer 1 if the sequence is
1778
empty.
1779
1780
EXAMPLES::
1781
1782
sage: from sage.structure.sequence import Sequence
1783
sage: from sage.rings.arith import __LCM_sequence
1784
sage: l = Sequence(())
1785
sage: __LCM_sequence(l)
1786
1
1787
1788
This is because lcm(0,x)=0 for all x (by convention)
1789
1790
::
1791
1792
sage: __LCM_sequence(Sequence(srange(100)))
1793
0
1794
1795
So for the lcm of all integers up to 10 you must do this::
1796
1797
sage: __LCM_sequence(Sequence(srange(1,100)))
1798
69720375229712477164533808935312303556800
1799
1800
Note that the following example did not work in QQ[] as of 2.11,
1801
but does in 3.1.4; the answer is different, though equivalent::
1802
1803
sage: R.<X>=ZZ[]
1804
sage: __LCM_sequence(Sequence((2*X+4,2*X^2,2)))
1805
2*X^3 + 4*X^2
1806
sage: R.<X>=QQ[]
1807
sage: __LCM_sequence(Sequence((2*X+4,2*X^2,2)))
1808
X^3 + 2*X^2
1809
"""
1810
if len(v) == 0:
1811
return ZZ(1)
1812
try:
1813
g = v.universe()(1)
1814
except AttributeError:
1815
g = ZZ(1)
1816
for vi in v:
1817
g = vi.lcm(g)
1818
if not g:
1819
return g
1820
return g
1821
1822
def xlcm(m,n):
1823
r"""
1824
Extended lcm function: given two positive integers `m,n`, returns
1825
a triple `(l,m_1,n_1)` such that `l=\mathop{\mathrm{lcm}}(m,n)=m_1
1826
\cdot n_1` where `m_1|m`, `n_1|n` and `\gcd(m_1,n_1)=1`, all with no
1827
factorization.
1828
1829
Used to construct an element of order `l` from elements of orders `m,n`
1830
in any group: see sage/groups/generic.py for examples.
1831
1832
EXAMPLES::
1833
1834
sage: xlcm(120,36)
1835
(360, 40, 9)
1836
"""
1837
g=gcd(m,n)
1838
l=m*n//g # = lcm(m,n)
1839
g=gcd(m,n//g) # divisible by those primes which divide n to a
1840
# higher power than m
1841
1842
while not g==1:
1843
m//=g
1844
g=gcd(m,g)
1845
1846
n=l//m;
1847
return (l,m,n)
1848
1849
def xgcd(a, b):
1850
r"""
1851
Return a triple ``(g,s,t)`` such that `g = s\cdot a+t\cdot b = \gcd(a,b)`.
1852
1853
.. note::
1854
1855
One exception is if `a` and `b` are not in a PID, e.g., they are
1856
both polynomials over the integers, then this function can't in
1857
general return ``(g,s,t)`` as above, since they need not exist.
1858
Instead, over the integers, we first multiply `g` by a divisor of
1859
the resultant of `a/g` and `b/g`, up to sign.
1860
1861
INPUT:
1862
1863
1864
- ``a, b`` - integers or univariate polynomials (or
1865
any type with an xgcd method).
1866
1867
1868
OUTPUT:
1869
1870
- ``g, s, t`` - such that `g = s\cdot a + t\cdot b`
1871
1872
1873
.. note::
1874
1875
There is no guarantee that the returned cofactors (s and t) are
1876
minimal. In the integer case, see
1877
:meth:`sage.rings.integer.Integer._xgcd()` for minimal
1878
cofactors.
1879
1880
EXAMPLES::
1881
1882
sage: xgcd(56, 44)
1883
(4, 4, -5)
1884
sage: 4*56 + (-5)*44
1885
4
1886
sage: g, a, b = xgcd(5/1, 7/1); g, a, b
1887
(1, 1/5, 0)
1888
sage: a*(5/1) + b*(7/1) == g
1889
True
1890
sage: x = polygen(QQ)
1891
sage: xgcd(x^3 - 1, x^2 - 1)
1892
(x - 1, 1, -x)
1893
sage: K.<g> = NumberField(x^2-3)
1894
sage: R.<a,b> = K[]
1895
sage: S.<y> = R.fraction_field()[]
1896
sage: xgcd(y^2, a*y+b)
1897
(1, a^2/b^2, ((-a)/b^2)*y + 1/b)
1898
sage: xgcd((b+g)*y^2, (a+g)*y+b)
1899
(1, (a^2 + (2*g)*a + 3)/(b^3 + (g)*b^2), ((-a + (-g))/b^2)*y + 1/b)
1900
1901
We compute an xgcd over the integers, where the linear combination
1902
is not the gcd but the resultant::
1903
1904
sage: R.<x> = ZZ[]
1905
sage: gcd(2*x*(x-1), x^2)
1906
x
1907
sage: xgcd(2*x*(x-1), x^2)
1908
(2*x, -1, 2)
1909
sage: (2*(x-1)).resultant(x)
1910
2
1911
"""
1912
try:
1913
return a.xgcd(b)
1914
except AttributeError:
1915
pass
1916
if not isinstance(a, sage.rings.integer.Integer):
1917
a = ZZ(a)
1918
return a.xgcd(ZZ(b))
1919
1920
XGCD = xgcd
1921
1922
## def XGCD_python(a, b):
1923
## """
1924
## Returns triple (g,p,q) such that g = p*a+b*q = GCD(a,b).
1925
## This function should behave exactly the same as XGCD,
1926
## but is implemented in pure python.
1927
## """
1928
## if a == 0 and b == 0:
1929
## return (0,0,1)
1930
## if a == 0:
1931
## return (abs(b), 0, b/abs(b))
1932
## if b == 0:
1933
## return (abs(a), a/abs(a), 0)
1934
## psign = 1
1935
## qsign = 1
1936
## if a < 0:
1937
## a = -a
1938
## psign = -1
1939
## if b < 0:
1940
## b = -b
1941
## qsign = -1
1942
## p = 1; q = 0; r = 0; s = 1
1943
## while b != 0:
1944
## c = a % b
1945
## quot = a/b
1946
## a = b; b = c
1947
## new_r = p - quot*r
1948
## new_s = q - quot*s
1949
## p = r; q = s
1950
## r = new_r; s = new_s
1951
## return (a, p*psign, q*qsign)
1952
1953
def inverse_mod(a, m):
1954
"""
1955
The inverse of the ring element a modulo m.
1956
1957
If no special inverse_mod is defined for the elements, it tries to
1958
coerce them into integers and perform the inversion there
1959
1960
::
1961
1962
sage: inverse_mod(7,1)
1963
0
1964
sage: inverse_mod(5,14)
1965
3
1966
sage: inverse_mod(3,-5)
1967
2
1968
"""
1969
try:
1970
return a.inverse_mod(m)
1971
except AttributeError:
1972
return integer.Integer(a).inverse_mod(m)
1973
1974
#######################################################
1975
# Functions to find the fastest available commands
1976
# for gcd and inverse_mod
1977
#######################################################
1978
1979
def get_gcd(order):
1980
"""
1981
Return the fastest gcd function for integers of size no larger than
1982
order.
1983
1984
EXAMPLES::
1985
1986
sage: sage.rings.arith.get_gcd(4000)
1987
<built-in method gcd_int of sage.rings.fast_arith.arith_int object at ...>
1988
sage: sage.rings.arith.get_gcd(400000)
1989
<built-in method gcd_longlong of sage.rings.fast_arith.arith_llong object at ...>
1990
sage: sage.rings.arith.get_gcd(4000000000)
1991
<function gcd at ...>
1992
"""
1993
if order <= 46340: # todo: don't hard code
1994
return fast_arith.arith_int().gcd_int
1995
elif order <= 2147483647: # todo: don't hard code
1996
return fast_arith.arith_llong().gcd_longlong
1997
else:
1998
return gcd
1999
2000
def get_inverse_mod(order):
2001
"""
2002
Return the fastest inverse_mod function for integers of size no
2003
larger than order.
2004
2005
EXAMPLES::
2006
2007
sage: sage.rings.arith.get_inverse_mod(6000)
2008
<built-in method inverse_mod_int of sage.rings.fast_arith.arith_int object at ...>
2009
sage: sage.rings.arith.get_inverse_mod(600000)
2010
<built-in method inverse_mod_longlong of sage.rings.fast_arith.arith_llong object at ...>
2011
sage: sage.rings.arith.get_inverse_mod(6000000000)
2012
<function inverse_mod at ...>
2013
"""
2014
if order <= 46340: # todo: don't hard code
2015
return fast_arith.arith_int().inverse_mod_int
2016
elif order <= 2147483647: # todo: don't hard code
2017
return fast_arith.arith_llong().inverse_mod_longlong
2018
else:
2019
return inverse_mod
2020
2021
# def sqrt_mod(a, m):
2022
# """A square root of a modulo m."""
2023
2024
# def xxx_inverse_mod(a, m):
2025
# """The inverse of a modulo m."""
2026
# g,s,t = XGCD(a,m)
2027
# if g != 1:
2028
# raise "inverse_mod(a=%s,m=%s), error since GCD=%s"%(a,m,g)
2029
# return s
2030
2031
def power_mod(a,n,m):
2032
"""
2033
The n-th power of a modulo the integer m.
2034
2035
EXAMPLES::
2036
2037
sage: power_mod(0,0,5)
2038
Traceback (most recent call last):
2039
...
2040
ArithmeticError: 0^0 is undefined.
2041
sage: power_mod(2,390,391)
2042
285
2043
sage: power_mod(2,-1,7)
2044
4
2045
sage: power_mod(11,1,7)
2046
4
2047
sage: R.<x> = ZZ[]
2048
sage: power_mod(3*x, 10, 7)
2049
4*x^10
2050
2051
sage: power_mod(11,1,0)
2052
Traceback (most recent call last):
2053
...
2054
ZeroDivisionError: modulus must be nonzero.
2055
"""
2056
if m==0:
2057
raise ZeroDivisionError, "modulus must be nonzero."
2058
if m==1:
2059
return 0
2060
if n < 0:
2061
ainv = inverse_mod(a,m)
2062
return power_mod(ainv, -n, m)
2063
if n==0:
2064
if a == 0:
2065
raise ArithmeticError, "0^0 is undefined."
2066
return 1
2067
2068
apow = a % m
2069
while n&1 == 0:
2070
apow = (apow*apow) % m
2071
n = n >> 1
2072
power = apow
2073
n = n >> 1
2074
while n != 0:
2075
apow = (apow*apow) % m
2076
if n&1 != 0:
2077
power = (power*apow) % m
2078
n = n >> 1
2079
2080
return power
2081
2082
2083
def rational_reconstruction(a, m, algorithm='fast'):
2084
r"""
2085
This function tries to compute `x/y`, where `x/y` is a rational number in
2086
lowest terms such that the reduction of `x/y` modulo `m` is equal to `a` and
2087
the absolute values of `x` and `y` are both `\le \sqrt{m/2}`. If such `x/y`
2088
exists, that pair is unique and this function returns it. If no
2089
such pair exists, this function raises ZeroDivisionError.
2090
2091
An efficient algorithm for computing rational reconstruction is
2092
very similar to the extended Euclidean algorithm. For more details,
2093
see Knuth, Vol 2, 3rd ed, pages 656-657.
2094
2095
INPUT:
2096
2097
- ``a`` - an integer
2098
2099
- ``m`` - a modulus
2100
2101
- ``algorithm`` - (default: 'fast')
2102
2103
- ``'fast'`` - a fast compiled implementation
2104
2105
- ``'python'`` - a slow pure python implementation
2106
2107
OUTPUT:
2108
2109
Numerator and denominator `n`, `d` of the unique rational number
2110
`r=n/d`, if it exists, with `n` and `|d| \le \sqrt{N/2}`. Return
2111
`(0,0)` if no such number exists.
2112
2113
The algorithm for rational reconstruction is described (with a
2114
complete nontrivial proof) on pages 656-657 of Knuth, Vol 2, 3rd
2115
ed. as the solution to exercise 51 on page 379. See in particular
2116
the conclusion paragraph right in the middle of page 657, which
2117
describes the algorithm thus:
2118
2119
This discussion proves that the problem can be solved
2120
efficiently by applying Algorithm 4.5.2X with `u=m` and `v=a`,
2121
but with the following replacement for step X2: If
2122
`v3 \le \sqrt{m/2}`, the algorithm terminates. The pair
2123
`(x,y)=(|v2|,v3*\mathrm{sign}(v2))` is then the unique
2124
solution, provided that `x` and `y` are coprime and
2125
`x \le \sqrt{m/2}`; otherwise there is no solution. (Alg 4.5.2X is
2126
the extended Euclidean algorithm.)
2127
2128
Knuth remarks that this algorithm is due to Wang, Kornerup, and
2129
Gregory from around 1983.
2130
2131
EXAMPLES::
2132
2133
sage: m = 100000
2134
sage: (119*inverse_mod(53,m))%m
2135
11323
2136
sage: rational_reconstruction(11323,m)
2137
119/53
2138
2139
::
2140
2141
sage: rational_reconstruction(400,1000)
2142
Traceback (most recent call last):
2143
...
2144
ValueError: Rational reconstruction of 400 (mod 1000) does not exist.
2145
2146
::
2147
2148
sage: rational_reconstruction(3,292393, algorithm='python')
2149
3
2150
sage: a = Integers(292393)(45/97); a
2151
204977
2152
sage: rational_reconstruction(a,292393, algorithm='python')
2153
45/97
2154
sage: a = Integers(292393)(45/97); a
2155
204977
2156
sage: rational_reconstruction(a,292393, algorithm='fast')
2157
45/97
2158
sage: rational_reconstruction(293048,292393, algorithm='fast')
2159
Traceback (most recent call last):
2160
...
2161
ValueError: Rational reconstruction of 655 (mod 292393) does not exist.
2162
sage: rational_reconstruction(293048,292393, algorithm='python')
2163
Traceback (most recent call last):
2164
...
2165
ValueError: Rational reconstruction of 655 (mod 292393) does not exist.
2166
2167
TESTS:
2168
2169
Check that ticket #9345 is fixed::
2170
2171
sage: rational_reconstruction(1, 0)
2172
Traceback (most recent call last):
2173
...
2174
ZeroDivisionError: The modulus cannot be zero
2175
sage: rational_reconstruction(randint(-10^6, 10^6), 0)
2176
Traceback (most recent call last):
2177
...
2178
ZeroDivisionError: The modulus cannot be zero
2179
"""
2180
if algorithm == 'fast':
2181
return ZZ(a).rational_reconstruction(m)
2182
elif algorithm == 'python':
2183
return _rational_reconstruction_python(a,m)
2184
else:
2185
raise ValueError("unknown algorithm")
2186
2187
def _rational_reconstruction_python(a,m):
2188
"""
2189
Internal fallback function for rational_reconstruction; see
2190
documentation of that function for details.
2191
2192
INPUT:
2193
2194
- ``a`` - an integer
2195
2196
- ``m`` - a modulus
2197
2198
EXAMPLES::
2199
2200
sage: from sage.rings.arith import _rational_reconstruction_python
2201
sage: _rational_reconstruction_python(20,31)
2202
-2/3
2203
sage: _rational_reconstruction_python(11323,100000)
2204
119/53
2205
"""
2206
a = int(a); m = int(m)
2207
a %= m
2208
if a == 0 or m==0:
2209
return ZZ(0)/ZZ(1)
2210
if m < 0:
2211
m = -m
2212
if a < 0:
2213
a = m-a
2214
if a == 1:
2215
return ZZ(1)/ZZ(1)
2216
u = m
2217
v = a
2218
bnd = math.sqrt(m/2)
2219
U = (1,0,u)
2220
V = (0,1,v)
2221
while abs(V[2]) > bnd:
2222
q = U[2]/V[2] # floor is implicit
2223
T = (U[0]-q*V[0], U[1]-q*V[1], U[2]-q*V[2])
2224
U = V
2225
V = T
2226
x = abs(V[1])
2227
y = V[2]
2228
if V[1] < 0:
2229
y *= -1
2230
if x <= bnd and GCD(x,y) == 1:
2231
return ZZ(y) / ZZ(x)
2232
raise ValueError, "Rational reconstruction of %s (mod %s) does not exist."%(a,m)
2233
2234
def mqrr_rational_reconstruction(u, m, T):
2235
r"""
2236
Maximal Quotient Rational Reconstruction.
2237
2238
For research purposes only - this is pure Python, so slow.
2239
2240
INPUT:
2241
2242
- ``u, m, T`` - integers such that `m > u \ge 0`, `T > 0`.
2243
2244
OUTPUT:
2245
2246
Either integers `n,d` such that `d>0`, `\mathop{\mathrm{gcd}}(n,d)=1`, `n/d=u \bmod m`, and
2247
`T \cdot d \cdot |n| < m`, or ``None``.
2248
2249
Reference: Monagan, Maximal Quotient Rational Reconstruction: An
2250
Almost Optimal Algorithm for Rational Reconstruction (page 11)
2251
2252
This algorithm is probabilistic.
2253
2254
EXAMPLES::
2255
2256
sage: mqrr_rational_reconstruction(21,3100,13)
2257
(21, 1)
2258
"""
2259
if u == 0:
2260
if m > T:
2261
return (0,1)
2262
else:
2263
return None
2264
n, d = 0, 0
2265
t0, r0 = 0, m
2266
t1, r1 = 1, u
2267
while r1 != 0 and r0 > T:
2268
q = r0/r1 # C division implicit floor
2269
if q > T:
2270
n, d, T = r1, t1, q
2271
r0, r1 = r1, r0 - q*r1
2272
t0, t1 = t1, t0 - q*t1
2273
if d != 0 and GCD(n,d) == 1:
2274
return (n,d)
2275
return None
2276
2277
2278
######################
2279
2280
2281
def trial_division(n, bound=None):
2282
"""
2283
Return the smallest prime divisor <= bound of the positive integer
2284
n, or n if there is no such prime. If the optional argument bound
2285
is omitted, then bound <= n.
2286
2287
INPUT:
2288
2289
- ``n`` - a positive integer
2290
2291
- ``bound`` - (optional) a positive integer
2292
2293
OUTPUT:
2294
2295
- ``int`` - a prime p=bound that divides n, or n if
2296
there is no such prime.
2297
2298
2299
EXAMPLES::
2300
2301
sage: trial_division(15)
2302
3
2303
sage: trial_division(91)
2304
7
2305
sage: trial_division(11)
2306
11
2307
sage: trial_division(387833, 300)
2308
387833
2309
sage: # 300 is not big enough to split off a
2310
sage: # factor, but 400 is.
2311
sage: trial_division(387833, 400)
2312
389
2313
"""
2314
if bound is None:
2315
return ZZ(n).trial_division()
2316
else:
2317
return ZZ(n).trial_division(bound)
2318
2319
def factor(n, proof=None, int_=False, algorithm='pari', verbose=0, **kwds):
2320
"""
2321
Returns the factorization of ``n``. The result depends on the
2322
type of ``n``.
2323
2324
If ``n`` is an integer, returns the factorization as an object
2325
of type ``Factorization``.
2326
2327
If n is not an integer, ``n.factor(proof=proof, **kwds)`` gets called.
2328
See ``n.factor??`` for more documentation in this case.
2329
2330
.. warning::
2331
2332
This means that applying ``factor`` to an integer result of
2333
a symbolic computation will not factor the integer, because it is
2334
considered as an element of a larger symbolic ring.
2335
2336
EXAMPLE::
2337
2338
sage: f(n)=n^2
2339
sage: is_prime(f(3))
2340
False
2341
sage: factor(f(3))
2342
9
2343
2344
INPUT:
2345
2346
- ``n`` - an nonzero integer
2347
2348
- ``proof`` - bool or None (default: None)
2349
2350
- ``int_`` - bool (default: False) whether to return
2351
answers as Python ints
2352
2353
- ``algorithm`` - string
2354
2355
- ``'pari'`` - (default) use the PARI c library
2356
2357
- ``'kash'`` - use KASH computer algebra system (requires the
2358
optional kash package be installed)
2359
2360
- ``'magma'`` - use Magma (requires magma be installed)
2361
2362
- ``verbose`` - integer (default: 0); PARI's debug
2363
variable is set to this; e.g., set to 4 or 8 to see lots of output
2364
during factorization.
2365
2366
OUTPUT:
2367
2368
- factorization of n
2369
2370
The qsieve and ecm commands give access to highly optimized
2371
implementations of algorithms for doing certain integer
2372
factorization problems. These implementations are not used by the
2373
generic factor command, which currently just calls PARI (note that
2374
PARI also implements sieve and ecm algorithms, but they aren't as
2375
optimized). Thus you might consider using them instead for certain
2376
numbers.
2377
2378
The factorization returned is an element of the class
2379
:class:`~sage.structure.factorization.Factorization`; see Factorization??
2380
for more details, and examples below for usage. A Factorization contains
2381
both the unit factor (+1 or -1) and a sorted list of (prime, exponent)
2382
pairs.
2383
2384
The factorization displays in pretty-print format but it is easy to
2385
obtain access to the (prime,exponent) pairs and the unit, to
2386
recover the number from its factorization, and even to multiply two
2387
factorizations. See examples below.
2388
2389
EXAMPLES::
2390
2391
sage: factor(500)
2392
2^2 * 5^3
2393
sage: factor(-20)
2394
-1 * 2^2 * 5
2395
sage: f=factor(-20)
2396
sage: list(f)
2397
[(2, 2), (5, 1)]
2398
sage: f.unit()
2399
-1
2400
sage: f.value()
2401
-20
2402
sage: factor( -next_prime(10^2) * next_prime(10^7) )
2403
-1 * 101 * 10000019
2404
2405
::
2406
2407
sage: factor(-500, algorithm='kash') # optional - kash
2408
-1 * 2^2 * 5^3
2409
2410
::
2411
2412
sage: factor(-500, algorithm='magma') # optional - magma
2413
-1 * 2^2 * 5^3
2414
2415
::
2416
2417
sage: factor(0)
2418
Traceback (most recent call last):
2419
...
2420
ArithmeticError: Prime factorization of 0 not defined.
2421
sage: factor(1)
2422
1
2423
sage: factor(-1)
2424
-1
2425
sage: factor(2^(2^7)+1)
2426
59649589127497217 * 5704689200685129054721
2427
2428
Sage calls PARI's factor, which has proof False by default.
2429
Sage has a global proof flag, set to True by default (see
2430
:mod:`sage.structure.proof.proof`, or proof.[tab]). To override
2431
the default, call this function with proof=False.
2432
2433
::
2434
2435
sage: factor(3^89-1, proof=False)
2436
2 * 179 * 1611479891519807 * 5042939439565996049162197
2437
2438
::
2439
2440
sage: factor(2^197 + 1) # long time (2s)
2441
3 * 197002597249 * 1348959352853811313 * 251951573867253012259144010843
2442
2443
Any object which has a factor method can be factored like this::
2444
2445
sage: K.<i> = QuadraticField(-1)
2446
sage: factor(122 - 454*i)
2447
(-1) * (-i - 4) * (-3*i - 2) * (-i - 2)^3 * (i + 1)^3
2448
2449
To access the data in a factorization::
2450
2451
sage: f = factor(420); f
2452
2^2 * 3 * 5 * 7
2453
sage: [x for x in f]
2454
[(2, 2), (3, 1), (5, 1), (7, 1)]
2455
sage: [p for p,e in f]
2456
[2, 3, 5, 7]
2457
sage: [e for p,e in f]
2458
[2, 1, 1, 1]
2459
sage: [p^e for p,e in f]
2460
[4, 3, 5, 7]
2461
2462
"""
2463
if isinstance(n, (int, long)):
2464
n = ZZ(n)
2465
2466
if isinstance(n, integer.Integer):
2467
return n.factor(proof=proof, algorithm=algorithm,
2468
int_ = int_, verbose=verbose)
2469
else:
2470
# e.g. n = x**2 + y**2 + 2*x*y
2471
try:
2472
return n.factor(proof=proof, **kwds)
2473
except AttributeError:
2474
raise TypeError, "unable to factor n"
2475
except TypeError:
2476
# Just in case factor method doesn't have a proof option.
2477
try:
2478
return n.factor(**kwds)
2479
except AttributeError:
2480
raise TypeError, "unable to factor n"
2481
2482
def radical(n, *args, **kwds):
2483
"""
2484
Return the product of the prime divisors of n.
2485
2486
This calls ``n.radical(*args, **kwds)``. If that doesn't work, it
2487
does ``n.factor(*args, **kwds)`` and returns the product of the prime
2488
factors in the resulting factorization.
2489
2490
EXAMPLES::
2491
2492
sage: radical(2 * 3^2 * 5^5)
2493
30
2494
sage: radical(0)
2495
Traceback (most recent call last):
2496
...
2497
ArithmeticError: Radical of 0 not defined.
2498
sage: K.<i> = QuadraticField(-1)
2499
sage: radical(K(2))
2500
i + 1
2501
2502
The next example shows how to compute the radical of a number,
2503
assuming no prime > 100000 has exponent > 1 in the factorization::
2504
2505
sage: n = 2^1000-1; n / radical(n, limit=100000)
2506
125
2507
"""
2508
try:
2509
return n.radical(*args, **kwds)
2510
except AttributeError:
2511
return n.factor(*args, **kwds).radical_value()
2512
2513
def prime_divisors(n):
2514
"""
2515
The prime divisors of ``n``.
2516
2517
INPUT:
2518
2519
- ``n`` -- any object which can be factored
2520
2521
OUTPUT:
2522
2523
A list of prime factors of ``n``. For integers, this list is sorted
2524
in increasing order.
2525
2526
EXAMPLES::
2527
2528
sage: prime_divisors(1)
2529
[]
2530
sage: prime_divisors(100)
2531
[2, 5]
2532
sage: prime_divisors(2004)
2533
[2, 3, 167]
2534
2535
If ``n`` is negative, we do *not* include -1 among the prime
2536
divisors, since -1 is not a prime number::
2537
2538
sage: prime_divisors(-100)
2539
[2, 5]
2540
2541
For polynomials we get all irreducible factors::
2542
2543
sage: R.<x> = PolynomialRing(QQ)
2544
sage: prime_divisors(x^12 - 1)
2545
[x - 1, x + 1, x^2 - x + 1, x^2 + 1, x^2 + x + 1, x^4 - x^2 + 1]
2546
"""
2547
return [p for p,_ in factor(n)]
2548
2549
prime_factors = prime_divisors
2550
2551
def odd_part(n):
2552
r"""
2553
The odd part of the integer `n`. This is `n / 2^v`,
2554
where `v = \mathrm{valuation}(n,2)`.
2555
2556
EXAMPLES::
2557
2558
sage: odd_part(5)
2559
5
2560
sage: odd_part(4)
2561
1
2562
sage: odd_part(factorial(31))
2563
122529844256906551386796875
2564
"""
2565
if not isinstance(n, integer.Integer):
2566
n = ZZ(n)
2567
return n.odd_part()
2568
2569
def prime_to_m_part(n,m):
2570
"""
2571
Returns the prime-to-m part of n, i.e., the largest divisor of n
2572
that is coprime to m.
2573
2574
INPUT:
2575
2576
2577
- ``n`` - Integer (nonzero)
2578
2579
- ``m`` - Integer
2580
2581
2582
OUTPUT: Integer
2583
2584
EXAMPLES::
2585
2586
sage: z = 43434
2587
sage: z.prime_to_m_part(20)
2588
21717
2589
"""
2590
if n == 0:
2591
raise ValueError, "n must be nonzero."
2592
if m == 0:
2593
return ZZ(1)
2594
n = ZZ(n)
2595
m = ZZ(m)
2596
while True:
2597
g = gcd(n,m)
2598
if g == 1:
2599
return n
2600
n = n // g
2601
2602
2603
def is_square(n, root=False):
2604
"""
2605
Returns whether or not n is square, and if n is a square also
2606
returns the square root. If n is not square, also returns None.
2607
2608
INPUT:
2609
2610
2611
- ``n`` - an integer
2612
2613
- ``root`` - whether or not to also return a square
2614
root (default: False)
2615
2616
2617
OUTPUT:
2618
2619
2620
- ``bool`` - whether or not a square
2621
2622
- ``object`` - (optional) an actual square if found,
2623
and None otherwise.
2624
2625
2626
EXAMPLES::
2627
2628
sage: is_square(2)
2629
False
2630
sage: is_square(4)
2631
True
2632
sage: is_square(2.2)
2633
True
2634
sage: is_square(-2.2)
2635
False
2636
sage: is_square(CDF(-2.2))
2637
True
2638
sage: is_square((x-1)^2)
2639
True
2640
2641
::
2642
2643
sage: is_square(4, True)
2644
(True, 2)
2645
"""
2646
try:
2647
if root:
2648
try:
2649
return n.is_square(root)
2650
except TypeError:
2651
if n.is_square():
2652
return True, n.sqrt()
2653
else:
2654
return False, None
2655
return n.is_square()
2656
except (AttributeError, NotImplementedError):
2657
pass
2658
t, x = pari(n).issquare(find_root=True)
2659
if root:
2660
if t:
2661
if hasattr(n, 'parent'):
2662
x = n.parent()(str(x))
2663
else:
2664
x = x.python()
2665
return t, x
2666
return t
2667
2668
2669
def is_squarefree(n):
2670
"""
2671
Returns True if and only if n is not divisible by the square of an
2672
integer > 1.
2673
2674
EXAMPLES::
2675
2676
sage: is_squarefree(100)
2677
False
2678
sage: is_squarefree(101)
2679
True
2680
"""
2681
if n==0:
2682
return False
2683
for p, r in factor(n):
2684
if r>1:
2685
return False
2686
return True
2687
2688
2689
#################################################################
2690
# Euler phi function
2691
#################################################################
2692
class Euler_Phi:
2693
r"""
2694
Return the value of the Euler phi function on the integer n. We
2695
defined this to be the number of positive integers <= n that are
2696
relatively prime to n. Thus if n<=0 then
2697
``euler_phi(n)`` is defined and equals 0.
2698
2699
INPUT:
2700
2701
2702
- ``n`` - an integer
2703
2704
2705
EXAMPLES::
2706
2707
sage: euler_phi(1)
2708
1
2709
sage: euler_phi(2)
2710
1
2711
sage: euler_phi(3)
2712
2
2713
sage: euler_phi(12)
2714
4
2715
sage: euler_phi(37)
2716
36
2717
2718
Notice that euler_phi is defined to be 0 on negative numbers and
2719
0.
2720
2721
::
2722
2723
sage: euler_phi(-1)
2724
0
2725
sage: euler_phi(0)
2726
0
2727
sage: type(euler_phi(0))
2728
<type 'sage.rings.integer.Integer'>
2729
2730
We verify directly that the phi function is correct for 21.
2731
2732
::
2733
2734
sage: euler_phi(21)
2735
12
2736
sage: [i for i in range(21) if gcd(21,i) == 1]
2737
[1, 2, 4, 5, 8, 10, 11, 13, 16, 17, 19, 20]
2738
2739
The length of the list of integers 'i' in range(n) such that the
2740
gcd(i,n) == 1 equals euler_phi(n).
2741
2742
::
2743
2744
sage: len([i for i in range(21) if gcd(21,i) == 1]) == euler_phi(21)
2745
True
2746
2747
The phi function also has a special plotting method.
2748
2749
::
2750
2751
sage: P = plot(euler_phi, -3, 71)
2752
2753
AUTHORS:
2754
2755
- William Stein
2756
2757
- Alex Clemesha (2006-01-10): some examples
2758
"""
2759
def __repr__(self):
2760
"""
2761
Returns a string describing this class.
2762
2763
EXAMPLES::
2764
2765
sage: Euler_Phi().__repr__()
2766
'Number of positive integers <=n but relatively prime to n'
2767
"""
2768
return "Number of positive integers <=n but relatively prime to n"
2769
2770
def __call__(self, n):
2771
"""
2772
Calls the euler_phi function.
2773
2774
EXAMPLES::
2775
2776
sage: Euler_Phi()(10)
2777
4
2778
sage: Euler_Phi()(720)
2779
192
2780
"""
2781
if n<=0:
2782
return ZZ(0)
2783
if n<=2:
2784
return ZZ(1)
2785
return ZZ(pari(n).phi())
2786
#return misc.mul([(p-1)*p**(r-1) for p, r in factor(n)])
2787
2788
def plot(self, xmin=1, xmax=50, pointsize=30, rgbcolor=(0,0,1), join=True,
2789
**kwds):
2790
"""
2791
Plot the Euler phi function.
2792
2793
INPUT:
2794
2795
2796
- ``xmin`` - default: 1
2797
2798
- ``xmax`` - default: 50
2799
2800
- ``pointsize`` - default: 30
2801
2802
- ``rgbcolor`` - default: (0,0,1)
2803
2804
- ``join`` - default: True; whether to join the
2805
points.
2806
2807
- ``**kwds`` - passed on
2808
2809
EXAMPLES::
2810
2811
sage: p = Euler_Phi().plot()
2812
sage: p.ymax()
2813
46.0
2814
"""
2815
v = [(n,euler_phi(n)) for n in range(xmin,xmax + 1)]
2816
from sage.plot.all import list_plot
2817
P = list_plot(v, pointsize=pointsize, rgbcolor=rgbcolor, **kwds)
2818
if join:
2819
P += list_plot(v, plotjoined=True, rgbcolor=(0.7,0.7,0.7), **kwds)
2820
return P
2821
2822
euler_phi = Euler_Phi()
2823
2824
def crt(a,b,m=None,n=None):
2825
r"""
2826
Returns a solution to a Chinese Remainder Theorem problem.
2827
2828
INPUT:
2829
2830
- ``a``, ``b`` - two residues (elements of some ring for which
2831
extended gcd is available), or two lists, one of residues and
2832
one of moduli.
2833
2834
- ``m``, ``n`` - (default: ``None``) two moduli, or ``None``.
2835
2836
OUTPUT:
2837
2838
If ``m``, ``n`` are not ``None``, returns a solution `x` to the
2839
simultaneous congruences `x\equiv a \bmod m` and `x\equiv b \bmod
2840
n`, if one exists. By the Chinese Remainder Theorem, a solution to the
2841
simultaneous congruences exists if and only if
2842
`a\equiv b\pmod{\gcd(m,n)}`. The solution `x` is only well-defined modulo
2843
`\text{lcm}(m,n)`.
2844
2845
If ``a`` and ``b`` are lists, returns a simultaneous solution to
2846
the congruences `x\equiv a_i\pmod{b_i}`, if one exists.
2847
2848
.. SEEALSO::
2849
2850
- :func:`CRT_list`
2851
2852
EXAMPLES:
2853
2854
Using ``crt`` by giving it pairs of residues and moduli::
2855
2856
sage: crt(2, 1, 3, 5)
2857
11
2858
sage: crt(13, 20, 100, 301)
2859
28013
2860
sage: crt([2, 1], [3, 5])
2861
11
2862
sage: crt([13, 20], [100, 301])
2863
28013
2864
2865
You can also use upper case::
2866
2867
sage: c = CRT(2,3, 3, 5); c
2868
8
2869
sage: c % 3 == 2
2870
True
2871
sage: c % 5 == 3
2872
True
2873
2874
Note that this also works for polynomial rings::
2875
2876
sage: K.<a> = NumberField(x^3 - 7)
2877
sage: R.<y> = K[]
2878
sage: f = y^2 + 3
2879
sage: g = y^3 - 5
2880
sage: CRT(1,3,f,g)
2881
-3/26*y^4 + 5/26*y^3 + 15/26*y + 53/26
2882
sage: CRT(1,a,f,g)
2883
(-3/52*a + 3/52)*y^4 + (5/52*a - 5/52)*y^3 + (15/52*a - 15/52)*y + 27/52*a + 25/52
2884
2885
You can also do this for any number of moduli::
2886
2887
sage: K.<a> = NumberField(x^3 - 7)
2888
sage: R.<x> = K[]
2889
sage: CRT([], [])
2890
0
2891
sage: CRT([a], [x])
2892
a
2893
sage: f = x^2 + 3
2894
sage: g = x^3 - 5
2895
sage: h = x^5 + x^2 - 9
2896
sage: k = CRT([1, a, 3], [f, g, h]); k
2897
(127/26988*a - 5807/386828)*x^9 + (45/8996*a - 33677/1160484)*x^8 + (2/173*a - 6/173)*x^7 + (133/6747*a - 5373/96707)*x^6 + (-6/2249*a + 18584/290121)*x^5 + (-277/8996*a + 38847/386828)*x^4 + (-135/4498*a + 42673/193414)*x^3 + (-1005/8996*a + 470245/1160484)*x^2 + (-1215/8996*a + 141165/386828)*x + 621/8996*a + 836445/386828
2898
sage: k.mod(f)
2899
1
2900
sage: k.mod(g)
2901
a
2902
sage: k.mod(h)
2903
3
2904
2905
If the moduli are not coprime, a solution may not exist::
2906
2907
sage: crt(4,8,8,12)
2908
20
2909
sage: crt(4,6,8,12)
2910
Traceback (most recent call last):
2911
...
2912
ValueError: No solution to crt problem since gcd(8,12) does not divide 4-6
2913
2914
sage: x = polygen(QQ)
2915
sage: crt(2,3,x-1,x+1)
2916
-1/2*x + 5/2
2917
sage: crt(2,x,x^2-1,x^2+1)
2918
-1/2*x^3 + x^2 + 1/2*x + 1
2919
sage: crt(2,x,x^2-1,x^3-1)
2920
Traceback (most recent call last):
2921
...
2922
ValueError: No solution to crt problem since gcd(x^2 - 1,x^3 - 1) does not divide 2-x
2923
2924
sage: crt(int(2), int(3), int(7), int(11))
2925
58
2926
"""
2927
if isinstance(a, list):
2928
return CRT_list(a, b)
2929
if isinstance(a, (int, long)):
2930
a = integer.Integer(a) # otherwise we get an error at (b-a).quo_rem(g)
2931
g, alpha, beta = XGCD(m, n)
2932
q, r = (b - a).quo_rem(g)
2933
if r != 0:
2934
raise ValueError("No solution to crt problem since gcd(%s,%s) does not divide %s-%s" % (m, n, a, b))
2935
return (a + q*alpha*m) % lcm(m, n)
2936
2937
CRT = crt
2938
2939
def CRT_list(v, moduli):
2940
r""" Given a list ``v`` of elements and a list of corresponding
2941
``moduli``, find a single element that reduces to each element of
2942
``v`` modulo the corresponding moduli.
2943
2944
.. SEEALSO::
2945
2946
- :func:`crt`
2947
2948
EXAMPLES::
2949
2950
sage: CRT_list([2,3,2], [3,5,7])
2951
23
2952
sage: x = polygen(QQ)
2953
sage: c = CRT_list([3], [x]); c
2954
3
2955
sage: c.parent()
2956
Univariate Polynomial Ring in x over Rational Field
2957
2958
It also works if the moduli are not coprime::
2959
2960
sage: CRT_list([32,2,2],[60,90,150])
2961
452
2962
2963
But with non coprime moduli there is not always a solution::
2964
2965
sage: CRT_list([32,2,1],[60,90,150])
2966
Traceback (most recent call last):
2967
...
2968
ValueError: No solution to crt problem since gcd(180,150) does not divide 92-1
2969
2970
The arguments must be lists::
2971
2972
sage: CRT_list([1,2,3],"not a list")
2973
Traceback (most recent call last):
2974
...
2975
ValueError: Arguments to CRT_list should be lists
2976
sage: CRT_list("not a list",[2,3])
2977
Traceback (most recent call last):
2978
...
2979
ValueError: Arguments to CRT_list should be lists
2980
2981
The list of moduli must have the same length as the list of elements::
2982
2983
sage: CRT_list([1,2,3],[2,3,5])
2984
23
2985
sage: CRT_list([1,2,3],[2,3])
2986
Traceback (most recent call last):
2987
...
2988
ValueError: Arguments to CRT_list should be lists of the same length
2989
sage: CRT_list([1,2,3],[2,3,5,7])
2990
Traceback (most recent call last):
2991
...
2992
ValueError: Arguments to CRT_list should be lists of the same length
2993
2994
TESTS::
2995
2996
sage: CRT([32r,2r,2r],[60r,90r,150r])
2997
452
2998
2999
"""
3000
if not isinstance(v,list) or not isinstance(moduli,list):
3001
raise ValueError, "Arguments to CRT_list should be lists"
3002
if len(v) != len(moduli):
3003
raise ValueError, "Arguments to CRT_list should be lists of the same length"
3004
if len(v) == 0:
3005
return ZZ(0)
3006
if len(v) == 1:
3007
return moduli[0].parent()(v[0])
3008
x = v[0]
3009
m = moduli[0]
3010
for i in range(1,len(v)):
3011
x = CRT(x,v[i],m,moduli[i])
3012
m = lcm(m,moduli[i])
3013
return x%m
3014
3015
def CRT_basis(moduli):
3016
r"""
3017
Returns a CRT basis for the given moduli.
3018
3019
INPUT:
3020
3021
- ``moduli`` - list of pairwise coprime moduli `m` which admit an
3022
extended Euclidean algorithm
3023
3024
OUTPUT:
3025
3026
- a list of elements `a_i` of the same length as `m` such that
3027
`a_i` is congruent to 1 modulo `m_i` and to 0 modulo `m_j` for
3028
`j\not=i`.
3029
3030
.. note::
3031
3032
The pairwise coprimality of the input is not checked.
3033
3034
EXAMPLES::
3035
3036
sage: a1 = ZZ(mod(42,5))
3037
sage: a2 = ZZ(mod(42,13))
3038
sage: c1,c2 = CRT_basis([5,13])
3039
sage: mod(a1*c1+a2*c2,5*13)
3040
42
3041
3042
A polynomial example::
3043
3044
sage: x=polygen(QQ)
3045
sage: mods = [x,x^2+1,2*x-3]
3046
sage: b = CRT_basis(mods)
3047
sage: b
3048
[-2/3*x^3 + x^2 - 2/3*x + 1, 6/13*x^3 - x^2 + 6/13*x, 8/39*x^3 + 8/39*x]
3049
sage: [[bi % mj for mj in mods] for bi in b]
3050
[[1, 0, 0], [0, 1, 0], [0, 0, 1]]
3051
"""
3052
n = len(moduli)
3053
if n == 0:
3054
return []
3055
M = prod(moduli)
3056
return [((xgcd(m,M//m)[2])*(M//m))%M for m in moduli]
3057
3058
def CRT_vectors(X, moduli):
3059
r"""
3060
Vector form of the Chinese Remainder Theorem: given a list of integer
3061
vectors `v_i` and a list of coprime moduli `m_i`, find a vector `w` such
3062
that `w = v_i \pmod m_i` for all `i`. This is more efficient than applying
3063
:func:`CRT` to each entry.
3064
3065
INPUT:
3066
3067
- ``X`` - list or tuple, consisting of lists/tuples/vectors/etc of
3068
integers of the same length
3069
- ``moduli`` - list of len(X) moduli
3070
3071
OUTPUT:
3072
3073
- ``list`` - application of CRT componentwise.
3074
3075
EXAMPLES::
3076
3077
sage: CRT_vectors([[3,5,7],[3,5,11]], [2,3])
3078
[3, 5, 5]
3079
3080
sage: CRT_vectors([vector(ZZ, [2,3,1]), Sequence([1,7,8],ZZ)], [8,9])
3081
[10, 43, 17]
3082
"""
3083
# First find the CRT basis:
3084
if len(X) == 0 or len(X[0]) == 0:
3085
return []
3086
n = len(X)
3087
if n != len(moduli):
3088
raise ValueError, "number of moduli must equal length of X"
3089
a = CRT_basis(moduli)
3090
modulus = misc.prod(moduli)
3091
return [sum([a[i]*X[i][j] for i in range(n)]) % modulus for j in range(len(X[0]))]
3092
3093
def binomial(x, m, **kwds):
3094
r"""
3095
Return the binomial coefficient
3096
3097
.. math::
3098
3099
\binom{x}{m} = x (x-1) \cdots (x-m+1) / m!
3100
3101
3102
which is defined for `m \in \ZZ` and any
3103
`x`. We extend this definition to include cases when
3104
`x-m` is an integer but `m` is not by
3105
3106
.. math::
3107
3108
\binom{x}{m}= \binom{x}{x-m}
3109
3110
If `m < 0`, return `0`.
3111
3112
INPUT:
3113
3114
- ``x``, ``m`` - numbers or symbolic expressions. Either ``m``
3115
or ``x-m`` must be an integer.
3116
3117
OUTPUT: number or symbolic expression (if input is symbolic)
3118
3119
EXAMPLES::
3120
3121
sage: binomial(5,2)
3122
10
3123
sage: binomial(2,0)
3124
1
3125
sage: binomial(1/2, 0)
3126
1
3127
sage: binomial(3,-1)
3128
0
3129
sage: binomial(20,10)
3130
184756
3131
sage: binomial(-2, 5)
3132
-6
3133
sage: binomial(-5, -2)
3134
0
3135
sage: binomial(RealField()('2.5'), 2)
3136
1.87500000000000
3137
sage: n=var('n'); binomial(n,2)
3138
1/2*(n - 1)*n
3139
sage: n=var('n'); binomial(n,n)
3140
1
3141
sage: n=var('n'); binomial(n,n-1)
3142
n
3143
sage: binomial(2^100, 2^100)
3144
1
3145
3146
sage: k, i = var('k,i')
3147
sage: binomial(k,i)
3148
binomial(k, i)
3149
3150
If `x \in \ZZ`, there is an optional 'algorithm' parameter, which
3151
can be 'mpir' (faster for small values) or 'pari' (faster for
3152
large values)::
3153
3154
sage: a = binomial(100, 45, algorithm='mpir')
3155
sage: b = binomial(100, 45, algorithm='pari')
3156
sage: a == b
3157
True
3158
3159
TESTS:
3160
3161
We test that certain binomials are very fast (this should be
3162
instant) -- see :trac:`3309`::
3163
3164
sage: a = binomial(RR(1140000.78), 23310000)
3165
3166
We test conversion of arguments to Integers -- see :trac:`6870`::
3167
3168
sage: binomial(1/2,1/1)
3169
1/2
3170
sage: binomial(10^20+1/1,10^20)
3171
100000000000000000001
3172
sage: binomial(SR(10**7),10**7)
3173
1
3174
sage: binomial(3/2,SR(1/1))
3175
3/2
3176
3177
Some floating point cases -- see :trac:`7562`, :trac:`9633`, and
3178
:trac:`12448`::
3179
3180
sage: binomial(1.,3)
3181
0.000000000000000
3182
sage: binomial(-2.,3)
3183
-4.00000000000000
3184
sage: binomial(0.5r, 5)
3185
0.02734375
3186
sage: a = binomial(float(1001), float(1)); a
3187
1001.0
3188
sage: type(a)
3189
<type 'float'>
3190
sage: binomial(float(1000), 1001)
3191
0.0
3192
3193
Test symbolic and uni/multivariate polynomials::
3194
3195
sage: K.<x> = ZZ[]
3196
sage: binomial(x,3)
3197
1/6*x^3 - 1/2*x^2 + 1/3*x
3198
sage: binomial(x,3).parent()
3199
Univariate Polynomial Ring in x over Rational Field
3200
sage: K.<x,y> = Integers(7)[]
3201
sage: binomial(y,3)
3202
-y^3 + 3*y^2 - 2*y
3203
sage: binomial(y,3).parent()
3204
Multivariate Polynomial Ring in x, y over Ring of integers modulo 7
3205
sage: n = var('n')
3206
sage: binomial(n,2)
3207
1/2*(n - 1)*n
3208
"""
3209
if isinstance(m,sage.symbolic.expression.Expression):
3210
try:
3211
# For performance reasons, we avoid to try to coerce
3212
# to Integer in the symbolic case (see #6870)
3213
m=m.pyobject()
3214
m=ZZ(m)
3215
except TypeError:
3216
pass
3217
else:
3218
try:
3219
m=ZZ(m)
3220
except TypeError:
3221
pass
3222
if not isinstance(m,integer.Integer):
3223
try:
3224
m = ZZ(x-m)
3225
except TypeError:
3226
try:
3227
return x.binomial(m)
3228
except AttributeError:
3229
pass
3230
raise TypeError('Either m or x-m must be an integer')
3231
if isinstance(x, (float, sage.rings.real_mpfr.RealNumber,
3232
sage.rings.real_mpfr.RealLiteral)):
3233
P = parent(x)
3234
# Try to convert x to an integer if it *is* an integer but of type
3235
# float. Otherwise, pari fails below in the case m > x.
3236
try:
3237
x = ZZ(x)
3238
except TypeError:
3239
pass
3240
if m < 0:
3241
return P(0)
3242
return P(pari(x).binomial(m))
3243
if isinstance(x,sage.symbolic.expression.Expression):
3244
try:
3245
x=x.pyobject()
3246
x=ZZ(x)
3247
except TypeError:
3248
pass
3249
else:
3250
try:
3251
x=ZZ(x)
3252
except TypeError:
3253
pass
3254
if isinstance(x,integer.Integer):
3255
if m < 0 or (x >= 0 and m > x):
3256
return ZZ.zero()
3257
3258
s = sys.maxint
3259
if m > s:
3260
m = x - m
3261
if m > s:
3262
raise ValueError("binomial not implemented for "
3263
"m > " + str(s) + ".\nThis is probably OK, "
3264
"since the answer would have "
3265
"billions of digits.")
3266
3267
return x.binomial(m, **kwds)
3268
try:
3269
P = x.parent()
3270
except AttributeError:
3271
P = type(x)
3272
if m < 0:
3273
return P(0)
3274
return misc.prod([x-i for i in xrange(m)])/factorial(m)
3275
3276
def multinomial(*ks):
3277
r"""
3278
Return the multinomial coefficient
3279
3280
INPUT:
3281
3282
- An arbitrary number of integer arguments `k_1,\dots,k_n`
3283
- A list of integers `[k_1,\dots,k_n]`
3284
3285
OUTPUT:
3286
3287
Returns the integer:
3288
3289
.. math::
3290
3291
\binom{k_1 + \cdots + k_n}{k_1, \cdots, k_n}
3292
=\frac{\left(\sum_{i=1}^n k_i\right)!}{\prod_{i=1}^n k_i!}
3293
= \prod_{i=1}^n \binom{\sum_{j=1}^i k_j}{k_i}
3294
3295
EXAMPLES::
3296
3297
sage: multinomial(0, 0, 2, 1, 0, 0)
3298
3
3299
sage: multinomial([0, 0, 2, 1, 0, 0])
3300
3
3301
sage: multinomial(3, 2)
3302
10
3303
sage: multinomial(2^30, 2, 1)
3304
618970023101454657175683075
3305
sage: multinomial([2^30, 2, 1])
3306
618970023101454657175683075
3307
3308
AUTHORS:
3309
3310
- Gabriel Ebner
3311
"""
3312
if isinstance(ks[0],list):
3313
if len(ks) >1:
3314
raise ValueError, "multinomial takes only one list argument"
3315
ks=ks[0]
3316
3317
s, c = 0, 1
3318
for k in ks:
3319
s += k
3320
c *= binomial(s, k)
3321
return c
3322
3323
def binomial_coefficients(n):
3324
r"""
3325
Return a dictionary containing pairs
3326
`\{(k_1,k_2) : C_{k,n}\}` where `C_{k_n}` are
3327
binomial coefficients and `n = k_1 + k_2`.
3328
3329
INPUT:
3330
3331
3332
- ``n`` - an integer
3333
3334
3335
OUTPUT: dict
3336
3337
EXAMPLES::
3338
3339
sage: sorted(binomial_coefficients(3).items())
3340
[((0, 3), 1), ((1, 2), 3), ((2, 1), 3), ((3, 0), 1)]
3341
3342
Notice the coefficients above are the same as below::
3343
3344
sage: R.<x,y> = QQ[]
3345
sage: (x+y)^3
3346
x^3 + 3*x^2*y + 3*x*y^2 + y^3
3347
3348
AUTHORS:
3349
3350
- Fredrik Johansson
3351
"""
3352
d = {(0, n):1, (n, 0):1}
3353
a = 1
3354
for k in xrange(1, n//2+1):
3355
a = (a * (n-k+1))//k
3356
d[k, n-k] = d[n-k, k] = a
3357
return d
3358
3359
def multinomial_coefficients(m, n):
3360
r"""
3361
Return a dictionary containing pairs
3362
`\{(k_1, k_2, ..., k_m) : C_{k, n}\}` where
3363
`C_{k, n}` are multinomial coefficients such that
3364
`n = k_1 + k_2 + ...+ k_m`.
3365
3366
INPUT:
3367
3368
- ``m`` - integer
3369
- ``n`` - integer
3370
3371
OUTPUT: dict
3372
3373
EXAMPLES::
3374
3375
sage: sorted(multinomial_coefficients(2, 5).items())
3376
[((0, 5), 1), ((1, 4), 5), ((2, 3), 10), ((3, 2), 10), ((4, 1), 5), ((5, 0), 1)]
3377
3378
Notice that these are the coefficients of `(x+y)^5`::
3379
3380
sage: R.<x,y> = QQ[]
3381
sage: (x+y)^5
3382
x^5 + 5*x^4*y + 10*x^3*y^2 + 10*x^2*y^3 + 5*x*y^4 + y^5
3383
3384
::
3385
3386
sage: sorted(multinomial_coefficients(3, 2).items())
3387
[((0, 0, 2), 1), ((0, 1, 1), 2), ((0, 2, 0), 1), ((1, 0, 1), 2), ((1, 1, 0), 2), ((2, 0, 0), 1)]
3388
3389
ALGORITHM: The algorithm we implement for computing the multinomial
3390
coefficients is based on the following result:
3391
3392
..math::
3393
3394
\binom{n}{k_1, \cdots, k_m} =
3395
\frac{k_1+1}{n-k_1}\sum_{i=2}^m \binom{n}{k_1+1, \cdots, k_i-1, \cdots}
3396
3397
e.g.::
3398
3399
sage: k = (2, 4, 1, 0, 2, 6, 0, 0, 3, 5, 7, 1) # random value
3400
sage: n = sum(k)
3401
sage: s = 0
3402
sage: for i in range(1, len(k)):
3403
... ki = list(k)
3404
... ki[0] += 1
3405
... ki[i] -= 1
3406
... s += multinomial(n, *ki)
3407
sage: multinomial(n, *k) == (k[0] + 1) / (n - k[0]) * s
3408
True
3409
3410
TESTS::
3411
3412
sage: multinomial_coefficients(0, 0)
3413
{(): 1}
3414
sage: multinomial_coefficients(0, 3)
3415
{}
3416
3417
"""
3418
if not m:
3419
if n:
3420
return {}
3421
else:
3422
return {(): 1}
3423
if m == 2:
3424
return binomial_coefficients(n)
3425
t = [n] + [0] * (m - 1)
3426
r = {tuple(t): 1}
3427
if n:
3428
j = 0 # j will be the leftmost nonzero position
3429
else:
3430
j = m
3431
# enumerate tuples in co-lex order
3432
while j < m - 1:
3433
# compute next tuple
3434
tj = t[j]
3435
if j:
3436
t[j] = 0
3437
t[0] = tj
3438
if tj > 1:
3439
t[j + 1] += 1
3440
j = 0
3441
start = 1
3442
v = 0
3443
else:
3444
j += 1
3445
start = j + 1
3446
v = r[tuple(t)]
3447
t[j] += 1
3448
# compute the value
3449
# NB: the initialization of v was done above
3450
for k in xrange(start, m):
3451
if t[k]:
3452
t[k] -= 1
3453
v += r[tuple(t)]
3454
t[k] += 1
3455
t[0] -= 1
3456
r[tuple(t)] = (v * tj) // (n - t[0])
3457
return r
3458
3459
# (since trac 14496) gaussian_binomial = sage.combinat.q_analogues.q_binomial
3460
3461
def kronecker_symbol(x,y):
3462
"""
3463
The Kronecker symbol `(x|y)`.
3464
3465
INPUT:
3466
3467
- ``x`` - integer
3468
3469
- ``y`` - integer
3470
3471
EXAMPLES::
3472
3473
sage: kronecker_symbol(13,21)
3474
-1
3475
sage: kronecker_symbol(101,4)
3476
1
3477
3478
IMPLEMENTATION: Using GMP.
3479
"""
3480
x = QQ(x).numerator() * QQ(x).denominator()
3481
return ZZ(x.kronecker(y))
3482
3483
def kronecker(x,y):
3484
r"""
3485
Synonym for :func:`kronecker_symbol`.
3486
3487
The Kronecker symbol `(x|y)`.
3488
3489
INPUT:
3490
3491
- ``x`` - integer
3492
3493
- ``y`` - integer
3494
3495
OUTPUT:
3496
3497
- an integer
3498
3499
EXAMPLES::
3500
3501
sage: kronecker(3,5)
3502
-1
3503
sage: kronecker(3,15)
3504
0
3505
sage: kronecker(2,15)
3506
1
3507
sage: kronecker(-2,15)
3508
-1
3509
sage: kronecker(2/3,5)
3510
1
3511
"""
3512
return kronecker_symbol(x,y)
3513
3514
def legendre_symbol(x,p):
3515
r"""
3516
The Legendre symbol `(x|p)`, for `p` prime.
3517
3518
.. note::
3519
3520
The :func:`kronecker_symbol` command extends the Legendre
3521
symbol to composite moduli and `p=2`.
3522
3523
INPUT:
3524
3525
3526
- ``x`` - integer
3527
3528
- ``p`` - an odd prime number
3529
3530
3531
EXAMPLES::
3532
3533
sage: legendre_symbol(2,3)
3534
-1
3535
sage: legendre_symbol(1,3)
3536
1
3537
sage: legendre_symbol(1,2)
3538
Traceback (most recent call last):
3539
...
3540
ValueError: p must be odd
3541
sage: legendre_symbol(2,15)
3542
Traceback (most recent call last):
3543
...
3544
ValueError: p must be a prime
3545
sage: kronecker_symbol(2,15)
3546
1
3547
sage: legendre_symbol(2/3,7)
3548
-1
3549
"""
3550
x = QQ(x).numerator() * QQ(x).denominator()
3551
p = ZZ(p)
3552
if not p.is_prime():
3553
raise ValueError, "p must be a prime"
3554
if p == 2:
3555
raise ValueError, "p must be odd"
3556
return x.kronecker(p)
3557
3558
def jacobi_symbol(a,b):
3559
r"""
3560
The Jacobi symbol of integers a and b, where b is odd.
3561
3562
.. note::
3563
3564
The :func:`kronecker_symbol` command extends the Jacobi
3565
symbol to all integers b.
3566
3567
If
3568
3569
`b = p_1^{e_1} * ... * p_r^{e_r}`
3570
3571
then
3572
3573
`(a|b) = (a|p_1)^{e_1} ... (a|p_r)^{e_r}`
3574
3575
where `(a|p_j)` are Legendre Symbols.
3576
3577
3578
3579
INPUT:
3580
3581
- ``a`` - an integer
3582
3583
- ``b`` - an odd integer
3584
3585
EXAMPLES::
3586
3587
sage: jacobi_symbol(10,777)
3588
-1
3589
sage: jacobi_symbol(10,5)
3590
0
3591
sage: jacobi_symbol(10,2)
3592
Traceback (most recent call last):
3593
...
3594
ValueError: second input must be odd, 2 is not odd
3595
"""
3596
3597
if b%2==0:
3598
raise ValueError, "second input must be odd, %s is not odd"%b
3599
3600
return kronecker_symbol(a,b)
3601
3602
3603
def primitive_root(n, check=True):
3604
"""
3605
Return a positive integer that generates the multiplicative group
3606
of integers modulo `n`, if one exists; otherwise, raise a
3607
``ValueError``.
3608
3609
A primitive root exists if `n=4` or `n=p^k` or `n=2p^k`, where `p`
3610
is an odd prime and `k` is a nonnegative number.
3611
3612
INPUT:
3613
3614
- ``n`` -- a non-zero integer
3615
- ``check`` -- bool (default: True); if False, then `n` is assumed
3616
to be a positive integer possessing a primitive root, and behavior
3617
is undefined otherwise.
3618
3619
OUTPUT:
3620
3621
A primitive root of `n`. If `n` is prime, this is the smallest
3622
primitive root.
3623
3624
EXAMPLES::
3625
3626
sage: primitive_root(23)
3627
5
3628
sage: primitive_root(-46)
3629
5
3630
sage: primitive_root(25)
3631
2
3632
sage: print [primitive_root(p) for p in primes(100)]
3633
[1, 2, 2, 3, 2, 2, 3, 2, 5, 2, 3, 2, 6, 3, 5, 2, 2, 2, 2, 7, 5, 3, 2, 3, 5]
3634
sage: primitive_root(8)
3635
Traceback (most recent call last):
3636
...
3637
ValueError: no primitive root
3638
3639
.. NOTE::
3640
3641
It takes extra work to check if `n` has a primitive root; to
3642
avoid this, use ``check=False``, which may slightly speed things
3643
up (but could also result in undefined behavior). For example,
3644
the second call below is an order of magnitude faster than the
3645
first:
3646
3647
::
3648
3649
sage: n = 10^50 + 151 # a prime
3650
sage: primitive_root(n)
3651
11
3652
sage: primitive_root(n, check=False)
3653
11
3654
3655
TESTS:
3656
3657
Various special cases::
3658
3659
sage: primitive_root(-1)
3660
0
3661
sage: primitive_root(0)
3662
Traceback (most recent call last):
3663
...
3664
ValueError: no primitive root
3665
sage: primitive_root(1)
3666
0
3667
sage: primitive_root(2)
3668
1
3669
sage: primitive_root(4)
3670
3
3671
3672
We test that various numbers without primitive roots give
3673
an error - see Trac 10836::
3674
3675
sage: primitive_root(15)
3676
Traceback (most recent call last):
3677
...
3678
ValueError: no primitive root
3679
sage: primitive_root(16)
3680
Traceback (most recent call last):
3681
...
3682
ValueError: no primitive root
3683
sage: primitive_root(1729)
3684
Traceback (most recent call last):
3685
...
3686
ValueError: no primitive root
3687
sage: primitive_root(4*7^8)
3688
Traceback (most recent call last):
3689
...
3690
ValueError: no primitive root
3691
"""
3692
if not check:
3693
return ZZ(pari(n).znprimroot())
3694
n = ZZ(n).abs()
3695
if n == 4:
3696
return ZZ(3)
3697
if n%2: # n odd
3698
if n.is_prime_power():
3699
return ZZ(pari(n).znprimroot())
3700
else: # n even
3701
m = n // 2
3702
if m%2 and m.is_prime_power():
3703
return ZZ(pari(n).znprimroot())
3704
raise ValueError, "no primitive root"
3705
3706
def nth_prime(n):
3707
"""
3708
3709
Return the n-th prime number (1-indexed, so that 2 is the 1st prime.)
3710
3711
INPUT:
3712
3713
- ``n`` -- a positive integer
3714
3715
OUTPUT:
3716
3717
- the n-th prime number
3718
3719
EXAMPLES::
3720
3721
sage: nth_prime(3)
3722
5
3723
sage: nth_prime(10)
3724
29
3725
3726
::
3727
3728
sage: nth_prime(0)
3729
Traceback (most recent call last):
3730
...
3731
ValueError: nth prime meaningless for non-positive n (=0)
3732
3733
TESTS::
3734
3735
sage: all(prime_pi(nth_prime(j)) == j for j in range(1, 1000, 10))
3736
True
3737
3738
"""
3739
return ZZ(pari.nth_prime(n))
3740
3741
def quadratic_residues(n):
3742
r"""
3743
Return a sorted list of all squares modulo the integer `n`
3744
in the range `0\leq x < |n|`.
3745
3746
EXAMPLES::
3747
3748
sage: quadratic_residues(11)
3749
[0, 1, 3, 4, 5, 9]
3750
sage: quadratic_residues(1)
3751
[0]
3752
sage: quadratic_residues(2)
3753
[0, 1]
3754
sage: quadratic_residues(8)
3755
[0, 1, 4]
3756
sage: quadratic_residues(-10)
3757
[0, 1, 4, 5, 6, 9]
3758
sage: v = quadratic_residues(1000); len(v);
3759
159
3760
"""
3761
n = abs(int(n))
3762
X = list(set([ZZ((a*a)%n) for a in range(n/2+1)]))
3763
X.sort()
3764
return X
3765
3766
## This much slower than above, for obvious reasons.
3767
## def quadratic_residues2(p):
3768
## return [x for x in range(p-1) if kronecker_symbol(x,p)==1]
3769
3770
class Moebius:
3771
r"""
3772
Returns the value of the Moebius function of abs(n), where n is an
3773
integer.
3774
3775
DEFINITION: `\mu(n)` is 0 if `n` is not square
3776
free, and otherwise equals `(-1)^r`, where `n` has
3777
`r` distinct prime factors.
3778
3779
For simplicity, if `n=0` we define `\mu(n) = 0`.
3780
3781
IMPLEMENTATION: Factors or - for integers - uses the PARI C
3782
library.
3783
3784
INPUT:
3785
3786
3787
- ``n`` - anything that can be factored.
3788
3789
3790
OUTPUT: 0, 1, or -1
3791
3792
EXAMPLES::
3793
3794
sage: moebius(-5)
3795
-1
3796
sage: moebius(9)
3797
0
3798
sage: moebius(12)
3799
0
3800
sage: moebius(-35)
3801
1
3802
sage: moebius(-1)
3803
1
3804
sage: moebius(7)
3805
-1
3806
3807
::
3808
3809
sage: moebius(0) # potentially nonstandard!
3810
0
3811
3812
The moebius function even makes sense for non-integer inputs.
3813
3814
::
3815
3816
sage: x = GF(7)['x'].0
3817
sage: moebius(x+2)
3818
-1
3819
"""
3820
def __call__(self, n):
3821
"""
3822
EXAMPLES::
3823
3824
sage: Moebius().__call__(7)
3825
-1
3826
"""
3827
if isinstance(n, (int, long)):
3828
n = ZZ(n)
3829
elif not isinstance(n, integer.Integer):
3830
# Use a generic algorithm.
3831
if n < 0:
3832
n = -n
3833
F = factor(n)
3834
for _, e in F:
3835
if e >= 2:
3836
return 0
3837
return (-1)**len(F)
3838
3839
# Use fast PARI algorithm
3840
if n == 0:
3841
return integer.Integer(0)
3842
return ZZ(pari(n).moebius())
3843
3844
3845
def __repr__(self):
3846
"""
3847
Returns a description of this function.
3848
3849
EXAMPLES::
3850
3851
sage: q = Moebius()
3852
sage: q.__repr__()
3853
'The Moebius function'
3854
"""
3855
return "The Moebius function"
3856
3857
def plot(self, xmin=0, xmax=50, pointsize=30, rgbcolor=(0,0,1), join=True,
3858
**kwds):
3859
"""
3860
Plot the Moebius function.
3861
3862
INPUT:
3863
3864
3865
- ``xmin`` - default: 0
3866
3867
- ``xmax`` - default: 50
3868
3869
- ``pointsize`` - default: 30
3870
3871
- ``rgbcolor`` - default: (0,0,1)
3872
3873
- ``join`` - default: True; whether to join the points
3874
(very helpful in seeing their order).
3875
3876
- ``**kwds`` - passed on
3877
3878
EXAMPLES::
3879
3880
sage: p = Moebius().plot()
3881
sage: p.ymax()
3882
1.0
3883
"""
3884
values = self.range(xmin, xmax + 1)
3885
v = [(n,values[n-xmin]) for n in range(xmin,xmax + 1)]
3886
from sage.plot.all import list_plot
3887
P = list_plot(v, pointsize=pointsize, rgbcolor=rgbcolor, **kwds)
3888
if join:
3889
P += list_plot(v, plotjoined=True, rgbcolor=(0.7,0.7,0.7), **kwds)
3890
return P
3891
3892
def range(self, start, stop=None, step=None):
3893
"""
3894
Return the Moebius function evaluated at the given range of values,
3895
i.e., the image of the list range(start, stop, step) under the
3896
Mobius function.
3897
3898
This is much faster than directly computing all these values with a
3899
list comprehension.
3900
3901
EXAMPLES::
3902
3903
sage: v = moebius.range(-10,10); v
3904
[1, 0, 0, -1, 1, -1, 0, -1, -1, 1, 0, 1, -1, -1, 0, -1, 1, -1, 0, 0]
3905
sage: v == [moebius(n) for n in range(-10,10)]
3906
True
3907
sage: v = moebius.range(-1000, 2000, 4)
3908
sage: v == [moebius(n) for n in range(-1000,2000, 4)]
3909
True
3910
"""
3911
if stop is None:
3912
start, stop = 1, int(start)
3913
else:
3914
start = int(start)
3915
stop = int(stop)
3916
if step is None:
3917
step = 1
3918
else:
3919
step = int(step)
3920
3921
Z = integer.Integer
3922
3923
if start <= 0 and 0 < stop and start % step == 0:
3924
return self.range(start, 0, step) + [Z(0)] +\
3925
self.range(step, stop, step)
3926
3927
if step == 1:
3928
v = pari('vector(%s, i, moebius(i-1+%s))'%(
3929
stop-start, start))
3930
else:
3931
n = len(range(start, stop, step)) # stupid
3932
v = pari('vector(%s, i, moebius(%s*(i-1) + %s))'%(
3933
n, step, start))
3934
return [Z(x) for x in v]
3935
3936
moebius = Moebius()
3937
3938
def farey(v, lim):
3939
"""
3940
Return the Farey sequence associated to the floating point number
3941
v.
3942
3943
INPUT:
3944
3945
3946
- ``v`` - float (automatically converted to a float)
3947
3948
- ``lim`` - maximum denominator.
3949
3950
3951
OUTPUT: Results are (numerator, denominator); (1, 0) is "infinity".
3952
3953
EXAMPLES::
3954
3955
sage: farey(2.0, 100)
3956
(2, 1)
3957
sage: farey(2.0, 1000)
3958
(2, 1)
3959
sage: farey(2.1, 1000)
3960
(21, 10)
3961
sage: farey(2.1, 100000)
3962
(21, 10)
3963
sage: farey(pi, 100000)
3964
(312689, 99532)
3965
3966
AUTHORS:
3967
3968
- Scott David Daniels: Python Cookbook, 2nd Ed., Recipe 18.13
3969
"""
3970
v = float(v)
3971
if v < 0:
3972
n, d = farey(-v, lim)
3973
return -n, d
3974
z = lim - lim # Get a "0 of the right type" for denominator
3975
lower, upper = (z, z+1), (z+1, z)
3976
while True:
3977
mediant = (lower[0] + upper[0]), (lower[1] + upper[1])
3978
if v * mediant[1] > mediant[0]:
3979
if lim < mediant[1]:
3980
return upper
3981
lower = mediant
3982
elif v * mediant[1] == mediant[0]:
3983
if lim >= mediant[1]:
3984
return mediant
3985
if lower[1] < upper[1]:
3986
return lower
3987
return upper
3988
else:
3989
if lim < mediant[1]:
3990
return lower
3991
upper = mediant
3992
3993
3994
## def convergents_pnqn(x):
3995
## """
3996
## Return the pairs (pn,qn) that are the numerators and denominators
3997
## of the partial convergents of the continued fraction of x. We
3998
## include (0,1) and (1,0) at the beginning of the list (these are
3999
## the -2 and -1 th convergents).
4000
## """
4001
## v = pari(x).contfrac()
4002
## w = [(0,1), (1,0)]
4003
## for n in range(len(v)):
4004
## pn = w[n+1][0]*v[n] + w[n][0]
4005
## qn = w[n+1][1]*v[n] + w[n][1]
4006
## w.append(int(pn), int(qn))
4007
## return w
4008
4009
def continued_fraction_list(x, partial_convergents=False, bits=None, nterms=None):
4010
r"""
4011
Returns the continued fraction of x as a list.
4012
4013
The continued fraction expansion of `x` are the coefficients `a_i` in
4014
4015
.. math::
4016
4017
x = a_1 + 1/(a_2+1/(...) ... )
4018
4019
with `a_1` integer and `a_2`, `...` positive integers.
4020
4021
.. note::
4022
4023
This may be slow for real number input, since it's implemented in pure
4024
Python. For rational number input the PARI C library is used.
4025
4026
.. SEEALSO::
4027
4028
:func:`Hirzebruch_Jung_continued_fraction_list` for
4029
Hirzebruch-Jung continued fractions.
4030
4031
INPUT:
4032
4033
- ``x`` -- exact rational or floating-point number. The number to
4034
compute the continued fraction of.
4035
4036
- ``partial_convergents`` -- boolean. Whether to return the partial convergents.
4037
4038
- ``bits`` -- integer. the precision of the real interval field
4039
that is used internally.
4040
4041
- ``nterms`` -- integer. The upper bound on the number of terms in
4042
the continued fraction expansion to return.
4043
4044
OUTPUT:
4045
4046
A lits of integers, the coefficients in the continued fraction
4047
expansion of ``x``. If ``partial_convergents=True`` is passed, a
4048
pair containing the coefficient list and the partial convergents
4049
list is returned.
4050
4051
EXAMPLES::
4052
4053
sage: continued_fraction_list(45/17)
4054
[2, 1, 1, 1, 5]
4055
sage: continued_fraction_list(e, bits=20)
4056
[2, 1, 2, 1, 1, 4, 1, 1]
4057
sage: continued_fraction_list(e, bits=30)
4058
[2, 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8]
4059
sage: continued_fraction_list(sqrt(2))
4060
[1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
4061
sage: continued_fraction_list(sqrt(4/19))
4062
[0, 2, 5, 1, 1, 2, 1, 16, 1, 2, 1, 1, 5, 4, 5, 1, 1, 2, 1]
4063
sage: continued_fraction_list(RR(pi), partial_convergents=True)
4064
([3, 7, 15, 1, 292, 1, 1, 1, 2, 1, 3, 1, 14, 3],
4065
[(3, 1),
4066
(22, 7),
4067
(333, 106),
4068
(355, 113),
4069
(103993, 33102),
4070
(104348, 33215),
4071
(208341, 66317),
4072
(312689, 99532),
4073
(833719, 265381),
4074
(1146408, 364913),
4075
(4272943, 1360120),
4076
(5419351, 1725033),
4077
(80143857, 25510582),
4078
(245850922, 78256779)])
4079
sage: continued_fraction_list(e)
4080
[2, 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8, 1, 1, 10, 1, 1, 12, 1, 1]
4081
sage: continued_fraction_list(RR(e))
4082
[2, 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8, 1, 1, 10, 1, 1, 12, 1, 1]
4083
sage: continued_fraction_list(RealField(200)(e))
4084
[2, 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8, 1, 1, 10, 1, 1, 12, 1, 1,
4085
14, 1, 1, 16, 1, 1, 18, 1, 1, 20, 1, 1, 22, 1, 1, 24, 1, 1,
4086
26, 1, 1, 28, 1, 1, 30, 1, 1, 32, 1, 1, 34, 1, 1, 36, 1, 1, 38, 1, 1]
4087
4088
TESTS::
4089
4090
sage: continued_fraction_list(1 + 10^-10, nterms=3)
4091
[1, 10000000000]
4092
sage: continued_fraction_list(1 + 10^-20 - e^-100, bits=10, nterms=3)
4093
[1, 100000000000000000000, 2688]
4094
sage: continued_fraction_list(1 + 10^-20 - e^-100, bits=10, nterms=5)
4095
[1, 100000000000000000000, 2688, 8, 1]
4096
sage: continued_fraction_list(1 + 10^-20 - e^-100, bits=1000, nterms=5)
4097
[1, 100000000000000000000, 2688, 8, 1]
4098
4099
Check that :trac:`14858` is fixed::
4100
4101
sage: continued_fraction_list(3/4) == continued_fraction_list(SR(3/4))
4102
True
4103
4104
"""
4105
if isinstance(x, sage.symbolic.expression.Expression):
4106
try:
4107
x = x.pyobject()
4108
except TypeError:
4109
pass
4110
4111
if isinstance(x, (integer.Integer, int, long)):
4112
if partial_convergents:
4113
return [x], [(x,1)]
4114
else:
4115
return [x]
4116
4117
if isinstance(x, sage.rings.rational.Rational):
4118
if bits is not None and nterms is None:
4119
x = RealIntervalField(bits)(x)
4120
else:
4121
# PARI is faster than the pure Python below, but doesn't give us the convergents.
4122
v = pari(x).contfrac().python()
4123
if nterms is not None:
4124
v = v[:nterms]
4125
if partial_convergents:
4126
w = [(0,1), (1,0)]
4127
for a in v:
4128
pn = a*w[-1][0] + w[-2][0]
4129
qn = a*w[-1][1] + w[-2][1]
4130
w.append((pn, qn))
4131
return v, w[2:]
4132
else:
4133
return v
4134
4135
# Work in interval field, increasing precision as needed.
4136
if bits is None:
4137
try:
4138
bits = x.prec()
4139
except AttributeError:
4140
bits = 53
4141
RIF = RealIntervalField(bits)
4142
v = []
4143
w = [(0,1), (1,0)]
4144
orig, x = x, RIF(x)
4145
4146
while True:
4147
try:
4148
a = x.unique_floor()
4149
except ValueError:
4150
# Either we're done or we need more precision.
4151
if nterms is None:
4152
break
4153
else:
4154
RIF = RIF.to_prec(2*RIF.prec())
4155
x = RIF(orig)
4156
for a in v: x = ~(x-a)
4157
continue
4158
if partial_convergents:
4159
pn = a*w[-1][0] + w[-2][0]
4160
qn = a*w[-1][1] + w[-2][1]
4161
w.append((pn, qn))
4162
v.append(a)
4163
if x == a or nterms is not None and len(v) >= nterms:
4164
break
4165
x = ~(x-a)
4166
4167
if partial_convergents:
4168
return v, w[2:]
4169
else:
4170
return v
4171
4172
4173
def Hirzebruch_Jung_continued_fraction_list(x, bits=None, nterms=None):
4174
r"""
4175
Return the Hirzebruch-Jung continued fraction of ``x`` as a list.
4176
4177
The Hirzebruch-Jung continued fraction of `x` is similar to the
4178
ordinary continued fraction expansion, but with minus signs. That
4179
is, the coefficients `a_i` in
4180
4181
.. math::
4182
4183
x = a_1 - 1/(a_2-1/(...) ... )
4184
4185
with `a_1` integer and `a_2`, `...` positive integers.
4186
4187
.. SEEALSO::
4188
4189
:func:`continued_fraction_list` for ordinary continued fractions.
4190
4191
INPUT:
4192
4193
- ``x`` -- exact rational or something that can be numerically
4194
evaluated. The number to compute the continued fraction of.
4195
4196
- ``bits`` -- integer (default: the precision of ``x``). the
4197
precision of the real interval field that is used
4198
internally. This is only used if ``x`` is not an exact fraction.
4199
4200
- ``nterms`` -- integer (default: None). The upper bound on the
4201
number of terms in the continued fraction expansion to return.
4202
4203
OUTPUT:
4204
4205
A lits of integers, the coefficients in the Hirzebruch-Jung continued
4206
fraction expansion of ``x``.
4207
4208
EXAMPLES::
4209
4210
sage: Hirzebruch_Jung_continued_fraction_list(17/11)
4211
[2, 3, 2, 2, 2, 2]
4212
sage: Hirzebruch_Jung_continued_fraction_list(45/17)
4213
[3, 3, 6]
4214
sage: Hirzebruch_Jung_continued_fraction_list(e, bits=20)
4215
[3, 4, 3, 2, 2, 2, 3, 7]
4216
sage: Hirzebruch_Jung_continued_fraction_list(e, bits=30)
4217
[3, 4, 3, 2, 2, 2, 3, 8, 3, 2, 2, 2, 2, 2, 2, 2, 3]
4218
sage: Hirzebruch_Jung_continued_fraction_list(sqrt(2), bits=100)
4219
[2, 2, 4, 2, 4, 2, 4, 2, 4, 2, 4, 2, 4, 2, 4, 2, 4, 2, 4, 2, 4, 2, 4, 2, 4,
4220
2, 4, 2, 4, 2, 4, 2, 4, 2, 4, 2, 4, 2, 4, 2, 2]
4221
sage: Hirzebruch_Jung_continued_fraction_list(sqrt(4/19))
4222
[1, 2, 7, 3, 2, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 3, 7,
4223
2, 2, 2, 7, 3, 2, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
4224
sage: Hirzebruch_Jung_continued_fraction_list(pi)
4225
[4, 2, 2, 2, 2, 2, 2, 17, 294, 3, 4, 5, 16, 2, 2]
4226
sage: Hirzebruch_Jung_continued_fraction_list(e)
4227
[3, 4, 3, 2, 2, 2, 3, 8, 3, 2, 2, 2, 2, 2, 2, 2,
4228
3, 12, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 10]
4229
sage: Hirzebruch_Jung_continued_fraction_list(e, nterms=20)
4230
[3, 4, 3, 2, 2, 2, 3, 8, 3, 2, 2, 2, 2, 2, 2, 2, 3, 12, 3, 2]
4231
sage: len(_) == 20
4232
True
4233
4234
TESTS::
4235
4236
sage: Hirzebruch_Jung_continued_fraction_list(1 - 10^-10, nterms=3)
4237
[1, 10000000000]
4238
sage: Hirzebruch_Jung_continued_fraction_list(1 - 10^-10 - e^-100, bits=100, nterms=5)
4239
[1, 10000000000]
4240
sage: Hirzebruch_Jung_continued_fraction_list(1 - 10^-20 - e^-100, bits=1000, nterms=5)
4241
[1, 100000000000000000000, 2689, 2, 2]
4242
"""
4243
if not isinstance(x, sage.rings.rational.Rational):
4244
try:
4245
x = QQ(x)
4246
except TypeError:
4247
# Numerically evaluate x
4248
if bits is None:
4249
try:
4250
bits = x.prec()
4251
except AttributeError:
4252
bits = 53
4253
x = QQ(x.n(bits))
4254
v = []
4255
while True:
4256
div, mod = divmod(x.numerator(), x.denominator())
4257
if mod == 0:
4258
v.append(div)
4259
break
4260
v.append(div+1)
4261
if nterms is not None and len(v) >= nterms:
4262
break
4263
x = 1/(div+1-x)
4264
return v
4265
4266
4267
def convergent(v, n):
4268
r"""
4269
Return the n-th continued fraction convergent of the continued
4270
fraction defined by the sequence of integers v. We assume
4271
`n \geq 0`.
4272
4273
INPUT:
4274
4275
4276
- ``v`` - list of integers
4277
4278
- ``n`` - integer
4279
4280
4281
OUTPUT: a rational number
4282
4283
If the continued fraction integers are
4284
4285
.. math::
4286
4287
v = [a_0, a_1, a_2, \ldots, a_k]
4288
4289
4290
then ``convergent(v,2)`` is the rational number
4291
4292
.. math::
4293
4294
a_0 + 1/a_1
4295
4296
and ``convergent(v,k)`` is the rational number
4297
4298
.. math::
4299
4300
a1 + 1/(a2+1/(...) ... )
4301
4302
represented by the continued fraction.
4303
4304
EXAMPLES::
4305
4306
sage: convergent([2, 1, 2, 1, 1, 4, 1, 1], 7)
4307
193/71
4308
"""
4309
if hasattr(v, 'convergent'):
4310
return v.convergent(n)
4311
i = int(n)
4312
x = QQ(v[i])
4313
i -= 1
4314
while i >= 0:
4315
x = QQ(v[i]) + 1/x
4316
i -= 1
4317
return x
4318
4319
4320
def convergents(v):
4321
"""
4322
Return all the partial convergents of a continued fraction defined
4323
by the sequence of integers v.
4324
4325
If v is not a list, compute the continued fraction of v and return
4326
its convergents (this is potentially much faster than calling
4327
continued_fraction first, since continued fractions are
4328
implemented using PARI and there is overhead moving the answer back
4329
from PARI).
4330
4331
INPUT:
4332
4333
4334
- ``v`` - list of integers or a rational number
4335
4336
4337
OUTPUT:
4338
4339
4340
- ``list`` - of partial convergents, as rational
4341
numbers
4342
4343
4344
EXAMPLES::
4345
4346
sage: convergents([2, 1, 2, 1, 1, 4, 1, 1])
4347
[2, 3, 8/3, 11/4, 19/7, 87/32, 106/39, 193/71]
4348
"""
4349
if hasattr(v, 'convergents'):
4350
return v.convergents()
4351
if not isinstance(v, list):
4352
v = pari(v).contfrac()
4353
w = [(0,1), (1,0)]
4354
for n in range(len(v)):
4355
pn = w[n+1][0]*v[n] + w[n][0]
4356
qn = w[n+1][1]*v[n] + w[n][1]
4357
w.append((pn, qn))
4358
return [QQ(x) for x in w[2:]]
4359
4360
4361
## def continuant(v, n=None):
4362
## """
4363
## Naive implementation with recursion.
4364
##
4365
## See Graham, Knuth and Patashnik: Concrete Mathematics: 6.7 Continuants
4366
## """
4367
## m = len(v)
4368
## if n == None or m < n:
4369
## n = m
4370
## if n == 0:
4371
## return 1
4372
## if n == 1:
4373
## return v[0]
4374
## return continuant(v[:n-1])*v[n-1] + continuant(v[:n-2])
4375
4376
def continuant(v, n=None):
4377
r"""
4378
Function returns the continuant of the sequence `v` (list
4379
or tuple).
4380
4381
Definition: see Graham, Knuth and Patashnik, *Concrete Mathematics*,
4382
section 6.7: Continuants. The continuant is defined by
4383
4384
- `K_0() = 1`
4385
- `K_1(x_1) = x_1`
4386
- `K_n(x_1, \cdots, x_n) = K_{n-1}(x_n, \cdots x_{n-1})x_n + K_{n-2}(x_1, \cdots, x_{n-2})`
4387
4388
If ``n = None`` or ``n > len(v)`` the default
4389
``n = len(v)`` is used.
4390
4391
INPUT:
4392
4393
- ``v`` - list or tuple of elements of a ring
4394
- ``n`` - optional integer
4395
4396
OUTPUT: element of ring (integer, polynomial, etcetera).
4397
4398
EXAMPLES::
4399
4400
sage: continuant([1,2,3])
4401
10
4402
sage: p = continuant([2, 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8, 1, 1, 10])
4403
sage: q = continuant([1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8, 1, 1, 10])
4404
sage: p/q
4405
517656/190435
4406
sage: convergent([2, 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8, 1, 1, 10],14)
4407
517656/190435
4408
sage: x = PolynomialRing(RationalField(),'x',5).gens()
4409
sage: continuant(x)
4410
x0*x1*x2*x3*x4 + x0*x1*x2 + x0*x1*x4 + x0*x3*x4 + x2*x3*x4 + x0 + x2 + x4
4411
sage: continuant(x, 3)
4412
x0*x1*x2 + x0 + x2
4413
sage: continuant(x,2)
4414
x0*x1 + 1
4415
4416
We verify the identity
4417
4418
.. math::
4419
4420
K_n(z,z,\cdots,z) = \sum_{k=0}^n \binom{n-k}{k} z^{n-2k}
4421
4422
for `n = 6` using polynomial arithmetic::
4423
4424
sage: z = QQ['z'].0
4425
sage: continuant((z,z,z,z,z,z,z,z,z,z,z,z,z,z,z),6)
4426
z^6 + 5*z^4 + 6*z^2 + 1
4427
4428
sage: continuant(9)
4429
Traceback (most recent call last):
4430
...
4431
TypeError: object of type 'sage.rings.integer.Integer' has no len()
4432
4433
AUTHORS:
4434
4435
- Jaap Spies (2007-02-06)
4436
"""
4437
m = len(v)
4438
if n == None or m < n:
4439
n = m
4440
if n == 0:
4441
return 1
4442
if n == 1:
4443
return v[0]
4444
a, b = 1, v[0]
4445
for k in range(1,n):
4446
a, b = b, a + b*v[k]
4447
return b
4448
4449
def number_of_divisors(n):
4450
"""
4451
Return the number of divisors of the integer n.
4452
4453
INPUT:
4454
4455
- ``n`` - a nonzero integer
4456
4457
OUTPUT:
4458
4459
- an integer, the number of divisors of n
4460
4461
EXAMPLES::
4462
4463
sage: number_of_divisors(100)
4464
9
4465
sage: number_of_divisors(-720)
4466
30
4467
"""
4468
m = ZZ(n)
4469
if m.is_zero():
4470
raise ValueError, "input must be nonzero"
4471
return ZZ(pari(m).numdiv())
4472
4473
4474
4475
def hilbert_symbol(a, b, p, algorithm="pari"):
4476
"""
4477
Returns 1 if `ax^2 + by^2` `p`-adically represents
4478
a nonzero square, otherwise returns `-1`. If either a or b
4479
is 0, returns 0.
4480
4481
INPUT:
4482
4483
4484
- ``a, b`` - integers
4485
4486
- ``p`` - integer; either prime or -1 (which
4487
represents the archimedean place)
4488
4489
- ``algorithm`` - string
4490
4491
- ``'pari'`` - (default) use the PARI C library
4492
4493
- ``'direct'`` - use a Python implementation
4494
4495
- ``'all'`` - use both PARI and direct and check that
4496
the results agree, then return the common answer
4497
4498
4499
OUTPUT: integer (0, -1, or 1)
4500
4501
EXAMPLES::
4502
4503
sage: hilbert_symbol (-1, -1, -1, algorithm='all')
4504
-1
4505
sage: hilbert_symbol (2,3, 5, algorithm='all')
4506
1
4507
sage: hilbert_symbol (4, 3, 5, algorithm='all')
4508
1
4509
sage: hilbert_symbol (0, 3, 5, algorithm='all')
4510
0
4511
sage: hilbert_symbol (-1, -1, 2, algorithm='all')
4512
-1
4513
sage: hilbert_symbol (1, -1, 2, algorithm='all')
4514
1
4515
sage: hilbert_symbol (3, -1, 2, algorithm='all')
4516
-1
4517
4518
sage: hilbert_symbol(QQ(-1)/QQ(4), -1, 2) == -1
4519
True
4520
sage: hilbert_symbol(QQ(-1)/QQ(4), -1, 3) == 1
4521
True
4522
4523
AUTHORS:
4524
4525
- William Stein and David Kohel (2006-01-05)
4526
"""
4527
p = ZZ(p)
4528
if p != -1 and not p.is_prime():
4529
raise ValueError, "p must be prime or -1"
4530
a = QQ(a).numerator() * QQ(a).denominator()
4531
b = QQ(b).numerator() * QQ(b).denominator()
4532
4533
if algorithm == "pari":
4534
return ZZ(pari(a).hilbert(b,p))
4535
4536
elif algorithm == 'direct':
4537
if a == 0 or b == 0:
4538
return ZZ(0)
4539
4540
p = ZZ(p)
4541
one = ZZ(1)
4542
4543
if p != -1:
4544
p_sqr = p**2
4545
while a%p_sqr == 0: a //= p_sqr
4546
while b%p_sqr == 0: b //= p_sqr
4547
4548
if p != 2 and True in ( kronecker(x,p) == 1 for x in (a,b,a+b) ):
4549
return one
4550
if a%p == 0:
4551
if b%p == 0:
4552
return hilbert_symbol(p,-(b//p),p)*hilbert_symbol(a//p,b,p)
4553
elif p == 2 and (b%4) == 3:
4554
if kronecker(a+b,p) == -1:
4555
return -one
4556
elif kronecker(b,p) == -1:
4557
return -one
4558
elif b%p == 0:
4559
if p == 2 and (a%4) == 3:
4560
if kronecker(a+b,p) == -1:
4561
return -one
4562
elif kronecker(a,p) == -1:
4563
return -one
4564
elif p == 2 and (a%4) == 3 and (b%4) == 3:
4565
return -one
4566
return one
4567
elif algorithm == 'all':
4568
ans_pari = hilbert_symbol(a,b,p,algorithm='pari')
4569
ans_direct = hilbert_symbol(a,b,p,algorithm='direct')
4570
if ans_pari != ans_direct:
4571
raise RuntimeError, "There is a bug in hilbert_symbol; two ways of computing the Hilbert symbol (%s,%s)_%s disagree"%(a,b,p)
4572
return ans_pari
4573
else:
4574
raise ValueError, "Algorithm %s not defined"%algorithm
4575
4576
4577
def hilbert_conductor(a, b):
4578
"""
4579
This is the product of all (finite) primes where the Hilbert symbol is -1.
4580
What is the same, this is the (reduced) discriminant of the quaternion
4581
algebra `(a,b)` over `\QQ`.
4582
4583
INPUT:
4584
4585
- ``a``, ``b`` -- integers
4586
4587
OUTPUT:
4588
4589
- squarefree positive integer
4590
4591
EXAMPLES::
4592
4593
sage: hilbert_conductor(-1, -1)
4594
2
4595
sage: hilbert_conductor(-1, -11)
4596
11
4597
sage: hilbert_conductor(-2, -5)
4598
5
4599
sage: hilbert_conductor(-3, -17)
4600
17
4601
4602
AUTHOR:
4603
4604
- Gonzalo Tornaria (2009-03-02)
4605
"""
4606
a, b = ZZ(a), ZZ(b)
4607
d = ZZ(1)
4608
for p in union(union( [2], prime_divisors(a) ), prime_divisors(b) ):
4609
if hilbert_symbol(a, b, p) == -1:
4610
d *= p
4611
return d
4612
4613
def hilbert_conductor_inverse(d):
4614
"""
4615
Finds a pair of integers `(a,b)` such that ``hilbert_conductor(a,b) == d``.
4616
The quaternion algebra `(a,b)` over `\QQ` will then have (reduced)
4617
discriminant `d`.
4618
4619
INPUT:
4620
4621
- ``d`` -- square-free positive integer
4622
4623
OUTPUT: pair of integers
4624
4625
EXAMPLES::
4626
4627
sage: hilbert_conductor_inverse(2)
4628
(-1, -1)
4629
sage: hilbert_conductor_inverse(3)
4630
(-1, -3)
4631
sage: hilbert_conductor_inverse(6)
4632
(-1, 3)
4633
sage: hilbert_conductor_inverse(30)
4634
(-3, -10)
4635
sage: hilbert_conductor_inverse(4)
4636
Traceback (most recent call last):
4637
...
4638
ValueError: d needs to be squarefree
4639
sage: hilbert_conductor_inverse(-1)
4640
Traceback (most recent call last):
4641
...
4642
ValueError: d needs to be positive
4643
4644
AUTHOR:
4645
4646
- Gonzalo Tornaria (2009-03-02)
4647
4648
TESTS::
4649
4650
sage: for i in xrange(100):
4651
... d = ZZ.random_element(2**32).squarefree_part()
4652
... if hilbert_conductor(*hilbert_conductor_inverse(d)) != d:
4653
... print "hilbert_conductor_inverse failed for d =", d
4654
"""
4655
Z = ZZ
4656
d = Z(d)
4657
if d <= 0:
4658
raise ValueError, "d needs to be positive"
4659
if d == 1:
4660
return (Z(-1), Z(1))
4661
if d == 2:
4662
return (Z(-1), Z(-1))
4663
if d.is_prime():
4664
if d%4 == 3:
4665
return (Z(-1), -d)
4666
if d%8 == 5:
4667
return (Z(-2), -d)
4668
q = 3
4669
while q%4 != 3 or kronecker_symbol(d,q) != -1:
4670
q = next_prime(q)
4671
return (Z(-q), -d)
4672
else:
4673
mo = moebius(d)
4674
if mo == 0:
4675
raise ValueError, "d needs to be squarefree"
4676
if d % 2 == 0 and mo*d % 16 != 2:
4677
dd = mo * d / 2
4678
else:
4679
dd = mo * d
4680
q = 1
4681
while hilbert_conductor(-q, dd) != d:
4682
q+=1;
4683
if dd%q == 0:
4684
dd /= q
4685
return (Z(-q), Z(dd))
4686
4687
4688
##############################################################################
4689
## falling and rising factorials
4690
## By Jaap Spies
4691
##
4692
## Copyright (C) 2006 Jaap Spies <[email protected]>
4693
## Copyright (C) 2006 William Stein <[email protected]>
4694
##
4695
## Distributed under the terms of the GNU General Public License (GPL)
4696
## http://www.gnu.org/licenses/
4697
##############################################################################
4698
4699
4700
def falling_factorial(x, a):
4701
r"""
4702
Returns the falling factorial `(x)_a`.
4703
4704
The notation in the literature is a mess: often `(x)_a`,
4705
but there are many other notations: GKP: Concrete Mathematics uses
4706
`x^{\underline{a}}`.
4707
4708
Definition: for integer `a \ge 0` we have
4709
`x(x-1) \cdots (x-a+1)`. In all other cases we use the
4710
GAMMA-function: `\frac {\Gamma(x+1)} {\Gamma(x-a+1)}`.
4711
4712
INPUT:
4713
4714
- ``x`` - element of a ring
4715
4716
- ``a`` - a non-negative integer or
4717
4718
OR
4719
4720
- ``x and a`` - any numbers
4721
4722
OUTPUT: the falling factorial
4723
4724
EXAMPLES::
4725
4726
sage: falling_factorial(10, 3)
4727
720
4728
sage: falling_factorial(10, RR('3.0'))
4729
720.000000000000
4730
sage: falling_factorial(10, RR('3.3'))
4731
1310.11633396601
4732
sage: falling_factorial(10, 10)
4733
3628800
4734
sage: factorial(10)
4735
3628800
4736
sage: a = falling_factorial(1+I, I); a
4737
gamma(I + 2)
4738
sage: CC(a)
4739
0.652965496420167 + 0.343065839816545*I
4740
sage: falling_factorial(1+I, 4)
4741
4*I + 2
4742
sage: falling_factorial(I, 4)
4743
-10
4744
4745
::
4746
4747
sage: M = MatrixSpace(ZZ, 4, 4)
4748
sage: A = M([1,0,1,0,1,0,1,0,1,0,10,10,1,0,1,1])
4749
sage: falling_factorial(A, 2) # A(A - I)
4750
[ 1 0 10 10]
4751
[ 1 0 10 10]
4752
[ 20 0 101 100]
4753
[ 2 0 11 10]
4754
4755
::
4756
4757
sage: x = ZZ['x'].0
4758
sage: falling_factorial(x, 4)
4759
x^4 - 6*x^3 + 11*x^2 - 6*x
4760
4761
Check that :trac:`14858` is fixed::
4762
4763
sage: falling_factorial(-4, SR(2))
4764
20
4765
4766
AUTHORS:
4767
4768
- Jaap Spies (2006-03-05)
4769
"""
4770
if (isinstance(a, (integer.Integer, int, long)) or
4771
(isinstance(a, sage.symbolic.expression.Expression) and
4772
a.is_integer())) and a >= 0:
4773
return misc.prod([(x - i) for i in range(a)])
4774
from sage.functions.all import gamma
4775
return gamma(x+1) / gamma(x-a+1)
4776
4777
def rising_factorial(x, a):
4778
r"""
4779
Returns the rising factorial `(x)^a`.
4780
4781
The notation in the literature is a mess: often `(x)^a`,
4782
but there are many other notations: GKP: Concrete Mathematics uses
4783
`x^{\overline{a}}`.
4784
4785
The rising factorial is also known as the Pochhammer symbol, see
4786
Maple and Mathematica.
4787
4788
Definition: for integer `a \ge 0` we have
4789
`x(x+1) \cdots (x+a-1)`. In all other cases we use the
4790
GAMMA-function: `\frac {\Gamma(x+a)} {\Gamma(x)}`.
4791
4792
INPUT:
4793
4794
4795
- ``x`` - element of a ring
4796
4797
- ``a`` - a non-negative integer or
4798
4799
- ``x and a`` - any numbers
4800
4801
4802
OUTPUT: the rising factorial
4803
4804
EXAMPLES::
4805
4806
sage: rising_factorial(10,3)
4807
1320
4808
4809
::
4810
4811
sage: rising_factorial(10,RR('3.0'))
4812
1320.00000000000
4813
4814
::
4815
4816
sage: rising_factorial(10,RR('3.3'))
4817
2826.38895824964
4818
4819
::
4820
4821
sage: a = rising_factorial(1+I, I); a
4822
gamma(2*I + 1)/gamma(I + 1)
4823
sage: CC(a)
4824
0.266816390637832 + 0.122783354006372*I
4825
4826
::
4827
4828
sage: a = rising_factorial(I, 4); a
4829
-10
4830
4831
See falling_factorial(I, 4).
4832
4833
::
4834
4835
sage: x = polygen(ZZ)
4836
sage: rising_factorial(x, 4)
4837
x^4 + 6*x^3 + 11*x^2 + 6*x
4838
4839
Check that :trac:`14858` is fixed::
4840
4841
sage: bool(rising_factorial(-4, 2) ==
4842
....: rising_factorial(-4, SR(2)) ==
4843
....: rising_factorial(SR(-4), SR(2)))
4844
True
4845
4846
AUTHORS:
4847
4848
- Jaap Spies (2006-03-05)
4849
"""
4850
if (isinstance(a, (integer.Integer, int, long)) or
4851
(isinstance(a, sage.symbolic.expression.Expression) and
4852
a.is_integer())) and a >= 0:
4853
return misc.prod([(x + i) for i in range(a)])
4854
from sage.functions.all import gamma
4855
return gamma(x+a) / gamma(x)
4856
4857
4858
def integer_ceil(x):
4859
"""
4860
Return the ceiling of x.
4861
4862
EXAMPLES::
4863
4864
sage: integer_ceil(5.4)
4865
6
4866
"""
4867
try:
4868
return sage.rings.all.Integer(x.ceil())
4869
except AttributeError:
4870
try:
4871
return sage.rings.all.Integer(int(math.ceil(float(x))))
4872
except TypeError:
4873
pass
4874
raise NotImplementedError, "computation of floor of %s not implemented"%repr(x)
4875
4876
def integer_floor(x):
4877
r"""
4878
Return the largest integer `\leq x`.
4879
4880
INPUT:
4881
4882
4883
- ``x`` - an object that has a floor method or is
4884
coercible to int
4885
4886
4887
OUTPUT: an Integer
4888
4889
EXAMPLES::
4890
4891
sage: integer_floor(5.4)
4892
5
4893
sage: integer_floor(float(5.4))
4894
5
4895
sage: integer_floor(-5/2)
4896
-3
4897
sage: integer_floor(RDF(-5/2))
4898
-3
4899
"""
4900
try:
4901
return ZZ(x.floor())
4902
except AttributeError:
4903
try:
4904
return ZZ(int(math.floor(float(x))))
4905
except TypeError:
4906
pass
4907
raise NotImplementedError, "computation of floor of %s not implemented"%x
4908
4909
4910
4911
def two_squares(n, algorithm='gap'):
4912
"""
4913
Write the integer n as a sum of two integer squares if possible;
4914
otherwise raise a ValueError.
4915
4916
EXAMPLES::
4917
4918
sage: two_squares(389)
4919
(10, 17)
4920
sage: two_squares(7)
4921
Traceback (most recent call last):
4922
...
4923
ValueError: 7 is not a sum of two squares
4924
sage: a,b = two_squares(2009); a,b
4925
(28, 35)
4926
sage: a^2 + b^2
4927
2009
4928
4929
TODO: Create an implementation using PARI's continued fraction
4930
implementation.
4931
"""
4932
from sage.rings.all import Integer
4933
n = Integer(n)
4934
4935
if algorithm == 'gap':
4936
import sage.interfaces.gap as gap
4937
a = gap.gap.eval('TwoSquares(%s)'%n)
4938
if a == 'fail':
4939
raise ValueError, "%s is not a sum of two squares"%n
4940
x, y = eval(a)
4941
return Integer(x), Integer(y)
4942
else:
4943
raise RuntimeError, "unknown algorithm '%s'"%algorithm
4944
4945
def _brute_force_four_squares(n):
4946
"""
4947
Brute force search for decomposition into a sum of four squares,
4948
for cases that the main algorithm fails to handle.
4949
4950
INPUT:
4951
4952
- ``n`` - a positive integer
4953
4954
OUTPUT:
4955
4956
- a list of four numbers whose squares sum to n
4957
4958
EXAMPLES::
4959
4960
sage: from sage.rings.arith import _brute_force_four_squares
4961
sage: _brute_force_four_squares(567)
4962
[1, 1, 6, 23]
4963
"""
4964
from math import sqrt
4965
for i in range(0,int(sqrt(n))+1):
4966
for j in range(i,int(sqrt(n-i**2))+1):
4967
for k in range(j, int(sqrt(n-i**2-j**2))+1):
4968
rem = n-i**2-j**2-k**2
4969
if rem >= 0:
4970
l = int(sqrt(rem))
4971
if rem-l**2==0:
4972
return [i,j,k,l]
4973
4974
def four_squares(n):
4975
"""
4976
Computes the decomposition into the sum of four squares,
4977
using an algorithm described by Peter Schorn at:
4978
http://www.schorn.ch/howto.html.
4979
4980
INPUT:
4981
4982
- ``n`` - an integer
4983
4984
OUTPUT:
4985
4986
- a list of four numbers whose squares sum to n
4987
4988
EXAMPLES::
4989
4990
sage: four_squares(3)
4991
[0, 1, 1, 1]
4992
sage: four_squares(130)
4993
[0, 0, 3, 11]
4994
sage: four_squares(1101011011004)
4995
[2, 1049178, 2370, 15196]
4996
sage: sum([i-sum([q^2 for q in four_squares(i)]) for i in range(2,10000)]) # long time
4997
0
4998
"""
4999
from sage.rings.finite_rings.integer_mod import mod
5000
from math import sqrt
5001
from sage.rings.arith import _brute_force_four_squares
5002
try:
5003
ts = two_squares(n)
5004
return [0,0,ts[0],ts[1]]
5005
except ValueError:
5006
pass
5007
m = n
5008
v = 0
5009
while mod(m,4) == 0:
5010
v = v +1
5011
m = m // 4
5012
if mod(m,8) == 7:
5013
d = 1
5014
m = m - 1
5015
else:
5016
d = 0
5017
if mod(m,8)==3:
5018
x = int(sqrt(m))
5019
if mod(x,2) == 0:
5020
x = x - 1
5021
p = (m-x**2) // 2
5022
while not is_prime(p):
5023
x = x - 2
5024
p = (m-x**2) // 2
5025
if x < 0:
5026
# fall back to brute force
5027
m = m + d
5028
return [2**v*q for q in _brute_force_four_squares(m)]
5029
y,z = two_squares(p)
5030
return [2**v*q for q in [d,x,y+z,abs(y-z)]]
5031
x = int(sqrt(m))
5032
p = m - x**2
5033
if p == 1:
5034
return[2**v*q for q in [d,0,x,1]]
5035
while not is_prime(p):
5036
x = x - 1
5037
p = m - x**2
5038
if x < 0:
5039
# fall back to brute force
5040
m = m + d
5041
return [2**v*q for q in _brute_force_four_squares(m)]
5042
y,z = two_squares(p)
5043
return [2**v*q for q in [d,x,y,z]]
5044
5045
5046
def subfactorial(n):
5047
r"""
5048
Subfactorial or rencontres numbers, or derangements: number of
5049
permutations of `n` elements with no fixed points.
5050
5051
INPUT:
5052
5053
5054
- ``n`` - non negative integer
5055
5056
5057
OUTPUT:
5058
5059
5060
- ``integer`` - function value
5061
5062
5063
EXAMPLES::
5064
5065
sage: subfactorial(0)
5066
1
5067
sage: subfactorial(1)
5068
0
5069
sage: subfactorial(8)
5070
14833
5071
5072
AUTHORS:
5073
5074
- Jaap Spies (2007-01-23)
5075
"""
5076
return factorial(n)*sum(((-1)**k)/factorial(k) for k in range(n+1))
5077
5078
5079
def is_power_of_two(n):
5080
r"""
5081
This function returns True if and only if `n` is a power of
5082
2
5083
5084
INPUT:
5085
5086
5087
- ``n`` - integer
5088
5089
5090
OUTPUT:
5091
5092
5093
- ``True`` - if n is a power of 2
5094
5095
- ``False`` - if not
5096
5097
5098
EXAMPLES::
5099
5100
sage: is_power_of_two(1024)
5101
True
5102
5103
::
5104
5105
sage: is_power_of_two(1)
5106
True
5107
5108
::
5109
5110
sage: is_power_of_two(24)
5111
False
5112
5113
::
5114
5115
sage: is_power_of_two(0)
5116
False
5117
5118
::
5119
5120
sage: is_power_of_two(-4)
5121
False
5122
5123
AUTHORS:
5124
5125
- Jaap Spies (2006-12-09)
5126
"""
5127
# modification of is2pow(n) from the Programming Guide
5128
while n > 0 and n%2 == 0:
5129
n = n >> 1
5130
return n == 1
5131
5132
def differences(lis, n=1):
5133
"""
5134
Returns the `n` successive differences of the elements in
5135
`lis`.
5136
5137
EXAMPLES::
5138
5139
sage: differences(prime_range(50))
5140
[1, 2, 2, 4, 2, 4, 2, 4, 6, 2, 6, 4, 2, 4]
5141
sage: differences([i^2 for i in range(1,11)])
5142
[3, 5, 7, 9, 11, 13, 15, 17, 19]
5143
sage: differences([i^3 + 3*i for i in range(1,21)])
5144
[10, 22, 40, 64, 94, 130, 172, 220, 274, 334, 400, 472, 550, 634, 724, 820, 922, 1030, 1144]
5145
sage: differences([i^3 - i^2 for i in range(1,21)], 2)
5146
[10, 16, 22, 28, 34, 40, 46, 52, 58, 64, 70, 76, 82, 88, 94, 100, 106, 112]
5147
sage: differences([p - i^2 for i, p in enumerate(prime_range(50))], 3)
5148
[-1, 2, -4, 4, -4, 4, 0, -6, 8, -6, 0, 4]
5149
5150
AUTHORS:
5151
5152
- Timothy Clemans (2008-03-09)
5153
"""
5154
n = ZZ(n)
5155
if n < 1:
5156
raise ValueError, 'n must be greater than 0'
5157
lis = [lis[i + 1] - num for i, num in enumerate(lis[:-1])]
5158
if n == 1:
5159
return lis
5160
return differences(lis, n - 1)
5161
5162
def _cmp_complex_for_display(a, b):
5163
r"""
5164
Compare two complex numbers in a "pretty" (but mathematically
5165
meaningless) fashion, for display only.
5166
5167
Real numbers (with a zero imaginary part) come before complex numbers,
5168
and are sorted. Complex numbers are sorted by their real part
5169
unless their real parts are quite close, in which case they are
5170
sorted by their imaginary part.
5171
5172
EXAMPLES::
5173
5174
sage: import sage.rings.arith
5175
sage: cmp_c = sage.rings.arith._cmp_complex_for_display
5176
sage: teeny = 3e-11
5177
sage: cmp_c(CC(5), CC(3, 3))
5178
-1
5179
sage: cmp_c(CC(3), CC(5, 5))
5180
-1
5181
sage: cmp_c(CC(5), CC(3))
5182
1
5183
sage: cmp_c(CC(teeny, -1), CC(-teeny, 1))
5184
-1
5185
sage: cmp_c(CC(teeny, 1), CC(-teeny, -1))
5186
1
5187
sage: cmp_c(CC(0, 1), CC(1, 0.5))
5188
-1
5189
sage: cmp_c(CC(3+teeny, -1), CC(3-teeny, 1))
5190
-1
5191
sage: CIF200 = ComplexIntervalField(200)
5192
sage: cmp_c(CIF200(teeny, -1), CIF200(-teeny, 1))
5193
-1
5194
sage: cmp_c(CIF200(teeny, 1), CIF200(-teeny, -1))
5195
1
5196
sage: cmp_c(CIF200(0, 1), CIF200(1, 0.5))
5197
-1
5198
sage: cmp_c(CIF200(3+teeny, -1), CIF200(3-teeny, 1))
5199
-1
5200
"""
5201
ar = a.real(); br = b.real()
5202
ai = a.imag(); bi = b.imag()
5203
epsilon = ar.parent()(1e-10)
5204
if ai:
5205
if bi:
5206
if abs(br) < epsilon:
5207
if abs(ar) < epsilon:
5208
return cmp(ai, bi)
5209
return cmp(ar, 0)
5210
if abs((ar - br) / br) < epsilon:
5211
return cmp(ai, bi)
5212
return cmp(ar, br)
5213
else:
5214
return 1
5215
else:
5216
if bi:
5217
return -1
5218
else:
5219
return cmp(ar, br)
5220
5221
def sort_complex_numbers_for_display(nums):
5222
r"""
5223
Given a list of complex numbers (or a list of tuples, where the
5224
first element of each tuple is a complex number), we sort the list
5225
in a "pretty" order. First come the real numbers (with zero
5226
imaginary part), then the complex numbers sorted according to
5227
their real part. If two complex numbers have a real part which is
5228
sufficiently close, then they are sorted according to their
5229
imaginary part.
5230
5231
This is not a useful function mathematically (not least because
5232
there's no principled way to determine whether the real components
5233
should be treated as equal or not). It is called by various
5234
polynomial root-finders; its purpose is to make doctest printing
5235
more reproducible.
5236
5237
We deliberately choose a cumbersome name for this function to
5238
discourage use, since it is mathematically meaningless.
5239
5240
EXAMPLES::
5241
5242
sage: import sage.rings.arith
5243
sage: sort_c = sort_complex_numbers_for_display
5244
sage: nums = [CDF(i) for i in range(3)]
5245
sage: for i in range(3):
5246
... nums.append(CDF(i + RDF.random_element(-3e-11, 3e-11),
5247
... RDF.random_element()))
5248
... nums.append(CDF(i + RDF.random_element(-3e-11, 3e-11),
5249
... RDF.random_element()))
5250
sage: shuffle(nums)
5251
sage: sort_c(nums)
5252
[0.0, 1.0, 2.0, -2.862406201e-11 - 0.708874026302*I, 2.2108362707e-11 - 0.436810529675*I, 1.00000000001 - 0.758765473764*I, 0.999999999976 - 0.723896589334*I, 1.99999999999 - 0.456080101207*I, 1.99999999999 + 0.609083628313*I]
5253
"""
5254
if len(nums) == 0:
5255
return nums
5256
5257
if isinstance(nums[0], tuple):
5258
return sorted(nums, cmp=_cmp_complex_for_display, key=lambda t: t[0])
5259
else:
5260
return sorted(nums, cmp=_cmp_complex_for_display)
5261
5262
def fundamental_discriminant(D):
5263
r"""
5264
Return the discriminant of the quadratic extension
5265
`K=Q(\sqrt{D})`, i.e. an integer d congruent to either 0 or
5266
1, mod 4, and such that, at most, the only square dividing it is
5267
4.
5268
5269
INPUT:
5270
5271
- ``D`` - an integer
5272
5273
OUTPUT:
5274
5275
- an integer, the fundamental discriminant
5276
5277
EXAMPLES::
5278
5279
sage: fundamental_discriminant(102)
5280
408
5281
sage: fundamental_discriminant(720)
5282
5
5283
sage: fundamental_discriminant(2)
5284
8
5285
5286
"""
5287
from sage.rings.all import Integer
5288
D = Integer(D)
5289
D = D.squarefree_part()
5290
if D%4 == 1:
5291
return D
5292
return 4*D
5293
5294
def squarefree_divisors(x):
5295
"""
5296
Iterator over the squarefree divisors (up to units) of the element x.
5297
5298
Depends on the output of the prime_divisors function.
5299
5300
INPUT::
5301
5302
x -- an element of any ring for which the prime_divisors
5303
function works.
5304
5305
EXAMPLES::
5306
5307
sage: list(squarefree_divisors(7))
5308
[1, 7]
5309
sage: list(squarefree_divisors(6))
5310
[1, 2, 3, 6]
5311
sage: list(squarefree_divisors(12))
5312
[1, 2, 3, 6]
5313
5314
"""
5315
p_list = prime_divisors(x)
5316
from sage.misc.misc import powerset
5317
for a in powerset(p_list):
5318
yield prod(a,1)
5319
5320
def dedekind_sum(p, q, algorithm='default'):
5321
r"""
5322
Return the Dedekind sum `s(p,q)` defined for integers `p`, `q` as
5323
5324
.. MATH::
5325
5326
s(p,q) = \sum_{i=0}^{q-1} \left(\!\left(\frac{i}{q}\right)\!\right)
5327
\left(\!\left(\frac{pi}{q}\right)\!\right)
5328
5329
where
5330
5331
.. MATH::
5332
5333
((x))=\begin{cases}
5334
x-\lfloor x \rfloor - \frac{1}{2} &\mbox{if }
5335
x \in \QQ \setminus \ZZ \\
5336
0 & \mbox{if } x \in \ZZ.
5337
\end{cases}
5338
5339
.. WARNING::
5340
5341
Caution is required as the Dedekind sum sometimes depends on the
5342
algorithm or is left undefined when `p` and `q` are not coprime.
5343
5344
INPUT:
5345
5346
- ``p``, ``q`` -- integers
5347
- ``algorithm`` -- must be one of the following
5348
5349
- ``'default'`` - (default) use FLINT
5350
- ``'flint'`` - use FLINT
5351
- ``'pari'`` - use PARI (gives different results if `p` and `q`
5352
are not coprime)
5353
5354
OUTPUT: a rational number
5355
5356
EXAMPLES:
5357
5358
Several small values::
5359
5360
sage: for q in range(10): print [dedekind_sum(p,q) for p in range(q+1)]
5361
[0]
5362
[0, 0]
5363
[0, 0, 0]
5364
[0, 1/18, -1/18, 0]
5365
[0, 1/8, 0, -1/8, 0]
5366
[0, 1/5, 0, 0, -1/5, 0]
5367
[0, 5/18, 1/18, 0, -1/18, -5/18, 0]
5368
[0, 5/14, 1/14, -1/14, 1/14, -1/14, -5/14, 0]
5369
[0, 7/16, 1/8, 1/16, 0, -1/16, -1/8, -7/16, 0]
5370
[0, 14/27, 4/27, 1/18, -4/27, 4/27, -1/18, -4/27, -14/27, 0]
5371
5372
Check relations for restricted arguments::
5373
5374
sage: q = 23; dedekind_sum(1, q); (q-1)*(q-2)/(12*q)
5375
77/46
5376
77/46
5377
sage: p, q = 100, 723 # must be coprime
5378
sage: dedekind_sum(p, q) + dedekind_sum(q, p)
5379
31583/86760
5380
sage: -1/4 + (p/q + q/p + 1/(p*q))/12
5381
31583/86760
5382
5383
We check that evaluation works with large input::
5384
5385
sage: dedekind_sum(3^54 - 1, 2^93 + 1)
5386
459340694971839990630374299870/29710560942849126597578981379
5387
sage: dedekind_sum(3^54 - 1, 2^93 + 1, algorithm='pari')
5388
459340694971839990630374299870/29710560942849126597578981379
5389
5390
Pari uses a different definition if the inputs are not coprime::
5391
5392
sage: dedekind_sum(5, 7, algorithm='default')
5393
-1/14
5394
sage: dedekind_sum(5, 7, algorithm='flint')
5395
-1/14
5396
sage: dedekind_sum(5, 7, algorithm='pari')
5397
-1/14
5398
sage: dedekind_sum(6, 8, algorithm='default')
5399
-1/8
5400
sage: dedekind_sum(6, 8, algorithm='flint')
5401
-1/8
5402
sage: dedekind_sum(6, 8, algorithm='pari')
5403
-1/24
5404
5405
REFERENCES:
5406
5407
.. [Apostol] T. Apostol, Modular functions and Dirichlet series
5408
in number theory, Springer, 1997 (2nd ed), section 3.7--3.9.
5409
5410
- :wikipedia:`Dedekind\_sum`
5411
"""
5412
if algorithm == 'default' or algorithm == 'flint':
5413
return flint_arith.dedekind_sum(p, q)
5414
5415
if algorithm == 'pari':
5416
import sage.interfaces.gp
5417
x = sage.interfaces.gp.gp('sumdedekind(%s,%s)' % (p, q))
5418
return sage.rings.rational.Rational(x)
5419
5420
raise ValueError('unknown algorithm')
5421
5422
5423