This repository has been archived by the owner on Jan 30, 2023. It is now read-only.
/
misc.py
5333 lines (4169 loc) · 142 KB
/
misc.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Miscellaneous arithmetic functions
"""
#*****************************************************************************
# Copyright (C) 2006 William Stein <wstein@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
# http://www.gnu.org/licenses/
#*****************************************************************************
from __future__ import absolute_import
import math
from sage.misc.misc import powerset
from sage.misc.misc_c import prod
from sage.libs.pari.all import pari
import sage.libs.flint.arith as flint_arith
from sage.structure.element import parent
from sage.structure.coerce import py_scalar_to_element
from sage.rings.rational_field import QQ
from sage.rings.integer_ring import ZZ
from sage.rings.integer import Integer, GCD_list, LCM_list
from sage.rings.rational import Rational
from sage.rings.real_mpfr import RealNumber
from sage.rings.complex_number import ComplexNumber
import sage.rings.fast_arith as fast_arith
prime_range = fast_arith.prime_range
##################################################################
# Elementary Arithmetic
##################################################################
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False):
"""
Returns a polynomial of degree at most `degree` which is
approximately satisfied by the number `z`. Note that the returned
polynomial need not be irreducible, and indeed usually won't be if
`z` is a good approximation to an algebraic number of degree less
than `degree`.
You can specify the number of known bits or digits of `z` with
``known_bits=k`` or ``known_digits=k``. PARI is then told to
compute the result using `0.8k` of these bits/digits. Or, you can
specify the precision to use directly with ``use_bits=k`` or
``use_digits=k``. If none of these are specified, then the precision
is taken from the input value.
A height bound may be specified to indicate the maximum coefficient
size of the returned polynomial; if a sufficiently small polynomial
is not found, then ``None`` will be returned. If ``proof=True`` then
the result is returned only if it can be proved correct (i.e. the
only possible minimal polynomial satisfying the height bound, or no
such polynomial exists). Otherwise a ``ValueError`` is raised
indicating that higher precision is required.
ALGORITHM: Uses LLL for real/complex inputs, PARI C-library
``algdep`` command otherwise.
Note that ``algebraic_dependency`` is a synonym for ``algdep``.
INPUT:
- ``z`` - real, complex, or `p`-adic number
- ``degree`` - an integer
- ``height_bound`` - an integer (default: ``None``) specifying the maximum
coefficient size for the returned polynomial
- ``proof`` - a boolean (default: ``False``), requires height_bound to be set
EXAMPLES::
sage: algdep(1.888888888888888, 1)
9*x - 17
sage: algdep(0.12121212121212,1)
33*x - 4
sage: algdep(sqrt(2),2)
x^2 - 2
This example involves a complex number::
sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z
0.500000000000000 + 0.866025403784439*I
sage: p = algdep(z, 6); p
x^3 + 1
sage: p.factor()
(x + 1) * (x^2 - x + 1)
sage: z^2 - z + 1 # abs tol 2e-16
0.000000000000000
This example involves a `p`-adic number::
sage: K = Qp(3, print_mode = 'series')
sage: a = K(7/19); a
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)
sage: algdep(a, 1)
19*x - 7
These examples show the importance of proper precision control. We
compute a 200-bit approximation to `sqrt(2)` which is wrong in the
33'rd bit::
sage: z = sqrt(RealField(200)(2)) + (1/2)^33
sage: p = algdep(z, 4); p
227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088
sage: factor(p)
227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088
sage: algdep(z, 4, known_bits=32)
x^2 - 2
sage: algdep(z, 4, known_digits=10)
x^2 - 2
sage: algdep(z, 4, use_bits=25)
x^2 - 2
sage: algdep(z, 4, use_digits=8)
x^2 - 2
Using the ``height_bound`` and ``proof`` parameters, we can see that
`pi` is not the root of an integer polynomial of degree at most 5
and coefficients bounded above by 10::
sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None
True
For stronger results, we need more precicion::
sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None
Traceback (most recent call last):
...
ValueError: insufficient precision for non-existence proof
sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None
True
sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None
Traceback (most recent call last):
...
ValueError: insufficient precision for non-existence proof
sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None
True
We can also use ``proof=True`` to get positive results::
sage: a = sqrt(2) + sqrt(3) + sqrt(5)
sage: algdep(a.n(), 8, height_bound=1000, proof=True)
Traceback (most recent call last):
...
ValueError: insufficient precision for uniqueness proof
sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f
x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576
sage: f(a).expand()
0
TESTS::
sage: algdep(complex("1+2j"), 4)
x^2 - 2*x + 5
"""
if proof and not height_bound:
raise ValueError("height_bound must be given for proof=True")
x = ZZ['x'].gen()
z = py_scalar_to_element(z)
if isinstance(z, Integer):
if height_bound and abs(z) >= height_bound:
return None
return x - ZZ(z)
degree = ZZ(degree)
if isinstance(z, Rational):
if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound:
return None
return z.denominator()*x - z.numerator()
if isinstance(z, (RealNumber, ComplexNumber)):
log2_10 = math.log(10,2)
prec = z.prec() - 6
if known_digits is not None:
known_bits = known_digits * log2_10
if known_bits is not None:
use_bits = known_bits * 0.8
if use_digits is not None:
use_bits = use_digits * log2_10
if use_bits is not None:
prec = int(use_bits)
is_complex = isinstance(z, ComplexNumber)
n = degree+1
from sage.matrix.all import matrix
M = matrix(ZZ, n, n+1+int(is_complex))
r = ZZ.one() << prec
M[0, 0] = 1
M[0, -1] = r
for k in range(1, degree+1):
M[k, k] = 1
r *= z
if is_complex:
M[k, -1] = r.real().round()
M[k, -2] = r.imag().round()
else:
M[k, -1] = r.round()
LLL = M.LLL(delta=.75)
coeffs = LLL[0][:n]
if height_bound:
def norm(v):
# norm on an integer vector invokes Integer.sqrt() which tries to factor...
from sage.rings.real_mpfi import RIF
return v.change_ring(RIF).norm()
if max(abs(a) for a in coeffs) > height_bound:
if proof:
# Given an LLL reduced basis $b_1, ..., b_n$, we only
# know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$.
if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound:
raise ValueError("insufficient precision for non-existence proof")
return None
elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound):
raise ValueError("insufficient precision for uniqueness proof")
if coeffs[degree] < 0:
coeffs = -coeffs
f = list(coeffs)
elif proof or height_bound:
raise NotImplementedError("proof and height bound only implemented for real and complex numbers")
else:
y = pari(z)
f = y.algdep(degree)
return x.parent()(f)
algebraic_dependency = algdep
def bernoulli(n, algorithm='default', num_threads=1):
r"""
Return the n-th Bernoulli number, as a rational number.
INPUT:
- ``n`` - an integer
- ``algorithm``:
- ``'default'`` -- use 'flint' for n <= 300000, and 'bernmm'
otherwise (this is just a heuristic, and not guaranteed to be
optimal on all hardware)
- ``'arb'`` -- use the arb library
- ``'flint'`` -- use the FLINT library
- ``'pari'`` -- use the PARI C library
- ``'gap'`` -- use GAP
- ``'gp'`` -- use PARI/GP interpreter
- ``'magma'`` -- use MAGMA (optional)
- ``'bernmm'`` -- use bernmm package (a multimodular algorithm)
- ``num_threads`` - positive integer, number of
threads to use (only used for bernmm algorithm)
EXAMPLES::
sage: bernoulli(12)
-691/2730
sage: bernoulli(50)
495057205241079648212477525/66
We demonstrate each of the alternative algorithms::
sage: bernoulli(12, algorithm='arb')
-691/2730
sage: bernoulli(12, algorithm='flint')
-691/2730
sage: bernoulli(12, algorithm='gap')
-691/2730
sage: bernoulli(12, algorithm='gp')
-691/2730
sage: bernoulli(12, algorithm='magma') # optional - magma
-691/2730
sage: bernoulli(12, algorithm='pari')
-691/2730
sage: bernoulli(12, algorithm='bernmm')
-691/2730
sage: bernoulli(12, algorithm='bernmm', num_threads=4)
-691/2730
TESTS::
sage: algs = ['arb','gap','gp','pari','bernmm','flint']
sage: test_list = [ZZ.random_element(2, 2255) for _ in range(500)]
sage: vals = [[bernoulli(i,algorithm = j) for j in algs] for i in test_list] # long time (up to 21s on sage.math, 2011)
sage: union([len(union(x))==1 for x in vals]) # long time (depends on previous line)
[True]
sage: algs = ['gp','pari','bernmm']
sage: test_list = [ZZ.random_element(2256, 5000) for _ in range(500)]
sage: vals = [[bernoulli(i,algorithm = j) for j in algs] for i in test_list] # long time (up to 30s on sage.math, 2011)
sage: union([len(union(x))==1 for x in vals]) # long time (depends on previous line)
[True]
AUTHOR:
- David Joyner and William Stein
"""
n = ZZ(n)
if algorithm == 'default':
algorithm = 'flint' if n <= 300000 else 'bernmm'
if algorithm == 'arb':
import sage.libs.arb.arith as arb_arith
return arb_arith.bernoulli(n)
elif algorithm == 'flint':
return flint_arith.bernoulli_number(n)
elif algorithm == 'pari':
x = pari(n).bernfrac() # Use the PARI C library
return Rational(x)
elif algorithm == 'gap':
import sage.interfaces.gap
x = sage.interfaces.gap.gap('Bernoulli(%s)'%n)
return Rational(x)
elif algorithm == 'magma':
import sage.interfaces.magma
x = sage.interfaces.magma.magma('Bernoulli(%s)'%n)
return Rational(x)
elif algorithm == 'gp':
import sage.interfaces.gp
x = sage.interfaces.gp.gp('bernfrac(%s)'%n)
return Rational(x)
elif algorithm == 'bernmm':
import sage.rings.bernmm
return sage.rings.bernmm.bernmm_bern_rat(n, num_threads)
else:
raise ValueError("invalid choice of algorithm")
def factorial(n, algorithm='gmp'):
r"""
Compute the factorial of `n`, which is the product
`1\cdot 2\cdot 3 \cdots (n-1)\cdot n`.
INPUT:
- ``n`` - an integer
- ``algorithm`` - string (default: 'gmp'):
- ``'gmp'`` - use the GMP C-library factorial function
- ``'pari'`` - use PARI's factorial function
OUTPUT: an integer
EXAMPLES::
sage: from sage.arith.misc import factorial
sage: factorial(0)
1
sage: factorial(4)
24
sage: factorial(10)
3628800
sage: factorial(1) == factorial(0)
True
sage: factorial(6) == 6*5*4*3*2
True
sage: factorial(1) == factorial(0)
True
sage: factorial(71) == 71* factorial(70)
True
sage: factorial(-32)
Traceback (most recent call last):
...
ValueError: factorial -- must be nonnegative
PERFORMANCE: This discussion is valid as of April 2006. All timings
below are on a Pentium Core Duo 2Ghz MacBook Pro running Linux with
a 2.6.16.1 kernel.
- It takes less than a minute to compute the factorial of
`10^7` using the GMP algorithm, and the factorial of
`10^6` takes less than 4 seconds.
- The GMP algorithm is faster and more memory efficient than the
PARI algorithm. E.g., PARI computes `10^7` factorial in 100
seconds on the core duo 2Ghz.
- For comparison, computation in Magma `\leq` 2.12-10 of
`n!` is best done using ``*[1..n]``. It takes
113 seconds to compute the factorial of `10^7` and 6
seconds to compute the factorial of `10^6`. Mathematica
V5.2 compute the factorial of `10^7` in 136 seconds and the
factorial of `10^6` in 7 seconds. (Mathematica is notably
very efficient at memory usage when doing factorial
calculations.)
"""
if n < 0:
raise ValueError("factorial -- must be nonnegative")
if algorithm == 'gmp':
return ZZ(n).factorial()
elif algorithm == 'pari':
return pari.factorial(n)
else:
raise ValueError('unknown algorithm')
def is_prime(n):
r"""
Return ``True`` if `n` is a prime number, and ``False`` otherwise.
Use a provable primality test or a strong pseudo-primality test depending
on the global :mod:`arithmetic proof flag <sage.structure.proof.proof>`.
INPUT:
- ``n`` - the object for which to determine primality
.. SEEALSO::
- :meth:`is_pseudoprime`
- :meth:`sage.rings.integer.Integer.is_prime`
AUTHORS:
- Kevin Stueve kstueve@uw.edu (2010-01-17):
delegated calculation to ``n.is_prime()``
EXAMPLES::
sage: is_prime(389)
True
sage: is_prime(2000)
False
sage: is_prime(2)
True
sage: is_prime(-1)
False
sage: is_prime(1)
False
sage: is_prime(-2)
False
sage: a = 2**2048 + 981
sage: is_prime(a) # not tested - takes ~ 1min
sage: proof.arithmetic(False)
sage: is_prime(a) # instantaneous!
True
sage: proof.arithmetic(True)
"""
try:
return n.is_prime()
except (AttributeError, NotImplementedError):
return ZZ(n).is_prime()
def is_pseudoprime(n, flag=None):
r"""
Test whether ``n`` is a pseudo-prime
The result is *NOT* proven correct - *this is a pseudo-primality test!*.
INPUT:
- ``n`` -- an integer
.. note::
We do not consider negatives of prime numbers as prime.
EXAMPLES::
sage: is_pseudoprime(389)
True
sage: is_pseudoprime(2000)
False
sage: is_pseudoprime(2)
True
sage: is_pseudoprime(-1)
False
sage: factor(-6)
-1 * 2 * 3
sage: is_pseudoprime(1)
False
sage: is_pseudoprime(-2)
False
TESTS:
Deprecation warning from :trac:`16878`::
sage: is_pseudoprime(127, flag=0)
doctest:...: DeprecationWarning: the keyword 'flag' is deprecated and no longer used
See http://trac.sagemath.org/16878 for details.
True
"""
if flag is not None:
from sage.misc.superseded import deprecation
deprecation(16878, "the keyword 'flag' is deprecated and no longer used")
return ZZ(n).is_pseudoprime()
def is_prime_power(n, flag=None, get_data=False):
r"""
Test whether ``n`` is a positive power of a prime number
This function simply calls the method :meth:`Integer.is_prime_power()
<sage.rings.integer.Integer.is_prime_power>` of Integers.
INPUT:
- ``n`` -- an integer
- ``get_data`` -- if set to ``True``, return a pair ``(p,k)`` such that
this integer equals ``p^k`` instead of ``True`` or ``(self,0)`` instead of
``False``
EXAMPLES::
sage: is_prime_power(389)
True
sage: is_prime_power(2000)
False
sage: is_prime_power(2)
True
sage: is_prime_power(1024)
True
sage: is_prime_power(1024, get_data=True)
(2, 10)
The same results can be obtained with::
sage: 389.is_prime_power()
True
sage: 2000.is_prime_power()
False
sage: 2.is_prime_power()
True
sage: 1024.is_prime_power()
True
sage: 1024.is_prime_power(get_data=True)
(2, 10)
TESTS::
sage: is_prime_power(-1)
False
sage: is_prime_power(1)
False
sage: is_prime_power(QQ(997^100))
True
sage: is_prime_power(1/2197)
Traceback (most recent call last):
...
TypeError: no conversion of this rational to integer
sage: is_prime_power("foo")
Traceback (most recent call last):
...
TypeError: unable to convert 'foo' to an integer
"""
if flag is not None:
from sage.misc.superseded import deprecation
deprecation(16878, "the keyword 'flag' is deprecated and no longer used")
return ZZ(n).is_prime_power(get_data=get_data)
def is_pseudoprime_power(n, get_data=False):
r"""
Test if ``n`` is a power of a pseudoprime.
The result is *NOT* proven correct - *this IS a pseudo-primality test!*.
Note that a prime power is a positive power of a prime number so that 1 is
not a prime power.
INPUT:
- ``n`` - an integer
- ``get_data`` - (boolean) instead of a boolean return a pair `(p,k)` so
that ``n`` equals `p^k` and `p` is a pseudoprime or `(n,0)` otherwise.
EXAMPLES::
sage: is_pseudoprime_power(389)
True
sage: is_pseudoprime_power(2000)
False
sage: is_pseudoprime_power(2)
True
sage: is_pseudoprime_power(1024)
True
sage: is_pseudoprime_power(-1)
False
sage: is_pseudoprime_power(1)
False
sage: is_pseudoprime_power(997^100)
True
Use of the get_data keyword::
sage: is_pseudoprime_power(3^1024, get_data=True)
(3, 1024)
sage: is_pseudoprime_power(2^256, get_data=True)
(2, 256)
sage: is_pseudoprime_power(31, get_data=True)
(31, 1)
sage: is_pseudoprime_power(15, get_data=True)
(15, 0)
"""
return ZZ(n).is_prime_power(proof=False, get_data=get_data)
def is_pseudoprime_small_power(n, bound=None, get_data=False):
"""
Deprecated version of ``is_pseudoprime_power``.
EXAMPLES::
sage: is_pseudoprime_small_power(1234)
doctest:...: DeprecationWarning: the function is_pseudoprime_small_power() is deprecated, use is_pseudoprime_power() instead.
See http://trac.sagemath.org/16878 for details.
False
sage: is_pseudoprime_small_power(3^1024, get_data=True)
[(3, 1024)]
"""
from sage.misc.superseded import deprecation
deprecation(16878, "the function is_pseudoprime_small_power() is deprecated, use is_pseudoprime_power() instead.")
if get_data:
return [ZZ(n).is_prime_power(proof=False, get_data=True)]
else:
return ZZ(n).is_prime_power(proof=False)
def valuation(m, *args, **kwds):
"""
Return the valuation of ``m``.
This function simply calls the m.valuation() method.
See the documentation of m.valuation() for a more precise description.
Note that the use of this functions is discouraged as it is better to use
m.valuation() directly.
.. NOTE::
This is not always a valuation in the mathematical sense.
For more information see:
sage.rings.finite_rings.integer_mod.IntegerMod_int.valuation
EXAMPLES::
sage: valuation(512,2)
9
sage: valuation(1,2)
0
sage: valuation(5/9, 3)
-2
Valuation of 0 is defined, but valuation with respect to 0 is not::
sage: valuation(0,7)
+Infinity
sage: valuation(3,0)
Traceback (most recent call last):
...
ValueError: You can only compute the valuation with respect to a integer larger than 1.
Here are some other examples::
sage: valuation(100,10)
2
sage: valuation(200,10)
2
sage: valuation(243,3)
5
sage: valuation(243*10007,3)
5
sage: valuation(243*10007,10007)
1
sage: y = QQ['y'].gen()
sage: valuation(y^3, y)
3
sage: x = QQ[['x']].gen()
sage: valuation((x^3-x^2)/(x-4))
2
sage: valuation(4r,2r)
2
sage: valuation(1r,1r)
Traceback (most recent call last):
...
ValueError: You can only compute the valuation with respect to a integer larger than 1.
"""
try:
return m.valuation(*args, **kwds)
except AttributeError:
return ZZ(m).valuation(*args, **kwds)
def prime_powers(start, stop=None):
r"""
List of all positive primes powers between ``start`` and
``stop``-1, inclusive. If the second argument is omitted, returns
the prime powers up to the first argument.
INPUT:
- ``start`` - an integer. If two inputs are given, a lower bound
for the returned set of prime powers. If this is the only input,
then it is an upper bound.
- ``stop`` - an integer (default: ``None``). An upper bound for the
returned set of prime powers.
OUTPUT:
The set of all prime powers between ``start`` and ``stop`` or, if
only one argument is passed, the set of all prime powers between 1
and ``start``. The number `n` is a prime power if `n=p^k`, where
`p` is a prime number and `k` is a positive integer. Thus, `1` is
not a prime power.
EXAMPLES::
sage: prime_powers(20)
[2, 3, 4, 5, 7, 8, 9, 11, 13, 16, 17, 19]
sage: len(prime_powers(1000))
193
sage: len(prime_range(1000))
168
sage: a = [z for z in range(95,1234) if is_prime_power(z)]
sage: b = prime_powers(95,1234)
sage: len(b)
194
sage: len(a)
194
sage: a[:10]
[97, 101, 103, 107, 109, 113, 121, 125, 127, 128]
sage: b[:10]
[97, 101, 103, 107, 109, 113, 121, 125, 127, 128]
sage: a == b
True
sage: prime_powers(100) == [i for i in range(100) if is_prime_power(i)]
True
sage: prime_powers(10,7)
[]
sage: prime_powers(-5)
[]
sage: prime_powers(-1,3)
[2]
TESTS:
Check that output are always Sage integers (:trac:`922`)::
sage: v = prime_powers(10)
sage: type(v[0])
<type 'sage.rings.integer.Integer'>
sage: prime_powers(0,1)
[]
sage: prime_powers(2)
[]
sage: prime_powers(3)
[2]
sage: prime_powers("foo")
Traceback (most recent call last):
...
TypeError: unable to convert 'foo' to an integer
sage: prime_powers(6, "bar")
Traceback (most recent call last):
...
TypeError: unable to convert 'bar' to an integer
Check that long input are accepted (:trac:`17852`)::
sage: prime_powers(6l)
[2, 3, 4, 5]
sage: prime_powers(6l,10l)
[7, 8, 9]
"""
start = ZZ(start)
ZZ_2 = Integer(2)
if stop is None:
stop = start
start = ZZ_2
else:
stop = ZZ(stop)
if stop <= ZZ_2 or start >= stop:
return []
output = []
for p in prime_range(stop):
q = p
while q < start:
q *= p
while q < stop:
output.append(q)
q *= p
output.sort()
return output
def primes_first_n(n, leave_pari=False):
r"""
Return the first `n` primes.
INPUT:
- `n` - a nonnegative integer
OUTPUT:
- a list of the first `n` prime numbers.
EXAMPLES::
sage: primes_first_n(10)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
sage: len(primes_first_n(1000))
1000
sage: primes_first_n(0)
[]
"""
if n < 0:
raise ValueError("n must be nonnegative")
if n < 1:
return []
return prime_range(nth_prime(n) + 1)
#
# This is from
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/366178
# It's impressively fast given that it's in Pure Python.
#
def eratosthenes(n):
r"""
Return a list of the primes `\leq n`.
This is extremely slow and is for educational purposes only.
INPUT:
- ``n`` - a positive integer
OUTPUT:
- a list of primes less than or equal to n.
EXAMPLES::
sage: eratosthenes(3)
[2, 3]
sage: eratosthenes(50)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
sage: len(eratosthenes(100))
25
sage: eratosthenes(213) == prime_range(213)
True
"""
n = int(n)
if n < 2:
return []
elif n == 2:
return [ZZ(2)]
s = range(3, n+3, 2)
mroot = int(n ** 0.5)
half = (n+1) // 2
i = 0
m = 3
while m <= mroot:
if s[i]:
j = (m*m-3) // 2
s[j] = 0
while j < half:
s[j] = 0
j += m
i = i+1
m = 2*i+3
return [ZZ(2)] + [ZZ(x) for x in s if x and x <= n]
def primes(start, stop=None, proof=None):
r"""
Returns an iterator over all primes between start and stop-1,
inclusive. This is much slower than ``prime_range``, but
potentially uses less memory. As with :func:`next_prime`, the optional
argument proof controls whether the numbers returned are
guaranteed to be prime or not.
This command is like the xrange command, except it only iterates
over primes. In some cases it is better to use primes than
``prime_range``, because primes does not build a list of all primes in
the range in memory all at once. However, it is potentially much
slower since it simply calls the :func:`next_prime` function
repeatedly, and :func:`next_prime` is slow.
INPUT:
- ``start`` - an integer - lower bound for the primes
- ``stop`` - an integer (or infinity) optional argument -
giving upper (open) bound for the primes
- ``proof`` - bool or None (default: None) If True, the function
yields only proven primes. If False, the function uses a
pseudo-primality test, which is much faster for really big
numbers but does not provide a proof of primality. If None,
uses the global default (see :mod:`sage.structure.proof.proof`)
OUTPUT:
- an iterator over primes from start to stop-1, inclusive
EXAMPLES::
sage: for p in primes(5,10):
....: print p
5
7
sage: list(primes(13))
[2, 3, 5, 7, 11]
sage: list(primes(10000000000, 10000000100))
[10000000019, 10000000033, 10000000061, 10000000069, 10000000097]
sage: max(primes(10^100, 10^100+10^4, proof=False))
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000009631
sage: next(p for p in primes(10^20, infinity) if is_prime(2*p+1))
100000000000000001243
TESTS::
sage: for a in range(-10, 50):
....: for b in range(-10, 50):
....: assert list(primes(a,b)) == list(filter(is_prime, xrange(a,b)))
sage: sum(primes(-10, 9973, proof=False)) == sum(filter(is_prime, range(-10, 9973)))
True
sage: for p in primes(10, infinity):
....: if p > 20: break
....: print p
11
13
17
19
sage: next(p for p in primes(10,oo)) # checks alternate infinity notation
11
"""
from sage.rings.infinity import infinity
start = ZZ(start)
if stop is None:
stop = start
start = ZZ(2)
elif stop != infinity:
stop = ZZ(stop)
n = start - 1
while True:
n = n.next_prime(proof)
if n < stop:
yield n
else:
return
def next_prime_power(n):
"""
Return the smallest prime power greater than ``n``.
Note that if ``n`` is a prime power, then this function does not return
``n``, but the next prime power after ``n``.
This function just calls the method
:meth:`Integer.next_prime_power() <sage.rings.integer.Integer.next_prime_power>`
of Integers.
.. SEEALSO::
- :func:`is_prime_power` (and
:meth:`Integer.is_prime_power() <sage.rings.integer.Integer.is_prime_power()>`)
- :func:`previous_prime_power` (and
:meth:`Integer.previous_prime_power() <sage.rings.integer.Integer.next_prime_power>`)
EXAMPLES::
sage: next_prime_power(1)