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