-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlabmath.py
5111 lines (4270 loc) · 188 KB
/
labmath.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
#! /usr/bin/env python3
# Formatting note: this file uses lines of up to 128 characters and employs 4-space chunks for indentations.
# Docstring lines are limited to 80 characters except for the occasional example output.
from multiprocessing import Process, Queue as mpQueue
from itertools import chain, count, groupby, islice, tee, cycle, takewhile, compress, product, zip_longest
from fractions import Fraction
from random import randrange
from math import log, log2, ceil, sqrt, factorial; inf = float('inf')
from heapq import merge
try: from gmpy2 import mpz; mpzv, inttypes = 2, (int, type(mpz(1)))
except ImportError: mpz, mpzv, inttypes = int, 0, (int,)
labmathversion = "2.2.0"
def primegen(limit=inf):
"""
Generates primes strictly less than limit almost lazily by a segmented
sieve of Eratosthenes. Memory usage depends on the sequence of prime
gaps; on Cramer's conjecture, it is O(sqrt(p) * log(p)^2).
Input: limit -- a number (default = inf)
Output: sequence of integers
Examples:
>>> list(islice(primegen(), 19))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67]
>>> list(primegen(71))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67]
"""
# We don't sieve 2, so we ought to be able to get sigificant savings by halving the length of the sieve.
# But the tiny extra computation involved in that seems to exceed the savings.
yield from takewhile(lambda x: x < limit, (2,3,5,7,11,13,17,19,23,29,31,37,41,43,47))
pl, pg = [3,5,7], primegen()
for p in pl: next(pg)
n = next(pg); nn = n*n
while True:
n = next(pg)
ll, nn = nn, n*n
sl = (nn - ll)
sieve = bytearray([True]) * sl
for p in pl:
k = (-ll) % p
sieve[k::p] = bytearray([False]) * ((sl-k)//p + 1)
if nn > limit: break # TODO bring this condition up to the while statement
yield from compress(range(ll,ll+sl,2), sieve[::2])
pl.append(n)
yield from takewhile(lambda x: x < limit, compress(range(ll,ll+sl,2), sieve[::2]))
def rpn(instr):
"""
Evaluates a string in reverse Polish notation.
The available binary operators are +, -, *, /, //, %, and **, which
all indicate the same operations here as they indicate in Python3
source code. The available unary operators are ! and #, which
denote the factorial and primorial, respectively. For terminal
syntax compatibility reasons, the RPN expression may be enclosed in
quotes, and four aliases are allowed: x for *, xx for **, f for !,
and p for #.
Input: instr -- a string
Output: A number
Examples:
>>> rpn("38 ! 1 +")
[523022617466601111760007224100074291200000001]
>>> rpn("1729 42 %")
[7]
>>> rpn("2 3 xx 5 6 7 +")
[8, 5, 13]
"""
stack = []
for token in instr.split():
if set(token).issubset("1234567890"): stack.append(int(token))
elif len(token) > 1 and token[0] == '-' and set(token[1:]).issubset("1234567890"): stack.append(int(token))
elif token in ('+', '-', '*', '/', '//', '%', '**', 'x', 'xx'): # binary operators
b = stack.pop()
a = stack.pop()
if token == '+' : res = a + b
elif token == '-' : res = a - b
elif token == '*' : res = a * b
elif token == 'x' : res = a * b
elif token == '/' : res = a / b
elif token == '//': res = a // b
elif token == '%' : res = a % b
elif token == '**': res = a ** b
elif token == 'xx': res = a ** b
stack.append(res)
elif token in ('!', 'f', '#', 'p'): # unary operators
a = stack.pop()
if token == '!' : res = iterprod(range(1, a+1))
elif token == 'f' : res = iterprod(range(1, a+1))
elif token == '#' : res = iterprod(primegen(a+1))
elif token == 'p' : res = iterprod(primegen(a+1))
stack.append(res)
else: raise Exception
return stack
def listprod(l):
"""
Product of the elements of a list. Product of empty list == 1.
We use a binary algorithm because this can easily generate huge numbers,
and calling "math.prod(l)", which amounts to "reduce(lambda x,y:x*y, l)",
in such situations is quite a bit slower. However, the size of the
problem required to make this superior to prod is quite large, so prod
should usually be used instead.
Input: l -- list of numbers
Output: A number
Examples:
>>> listprod(range(1, 8))
5040
"""
if len(l) == 0: return 1
while len(l) > 1:
q = [l[2*t] * l[2*t+1] for t in range(len(l) // 2)]
if len(l) % 2 == 1: q.append(l[-1])
l = q
return l[0]
def iterprod(l): # TODO: When PyPy3 supports Python 3.8, replace with "from math import prod".
"""
Product of the elements of any iterable. Empty product == 1.
DEPRECATION WARNING: now that Python 3.8 has math.prod, this function
definition will in a future version be replaced with the statement
"from math import prod". That will probably happen when PyPy3 supports
Python 3.8.
Input: l -- iterable
Output: A number
Examples:
>>> iterprod(range(1, 8))
5040
"""
z = 1
for x in l: z *= x
return z
def polyval(f, x, m=None):
"""
Evalutates a polynomial at a particular point, optionally modulo m.
Input:
f -- List. These are the polynomial's coefficients in order of
increasing degree.
x -- Integer. Evaluate here.
m -- Integer or None (default). If not None, evaluate modulo m.
Output: An integer.
Examples:
>>> polyval([1,2,3], 2)
17
>>> polyval([1,2,3], 2, 3)
2
"""
out = 0
if m is None:
for a in reversed(f): out = a + out * x
else:
for a in reversed(f): out = (a + out * x) % m
return out
def binomial(n, k): # TODO: When PyPy3 supports Python 3.8, replace with "from math import comb".
"""
Calculates the binomial coefficient nCr(n,k).
DEPRECATION WARNING: now that Python 3.8 has math.comb, this function
definition will in a future version be replaced with the statement
"from math import comb". That will probably happen when PyPy3 supports
Python 3.8.
Input: n, k -- non-negative integers
Output: Integer
Examples:
>>> binomial(30,12)
86493225
"""
nt = 1
for t in range(min(k, n-k)):
nt *= n - t
nt //= t + 1
return nt
def powerset(l): # TODO: make this handle sets as well.
"""
Generates the powerset of a list, tuple, or string. Output is a list.
Input: l -- indexable iterable
Output: Sequence of lists
Examples:
>>> list(powerset([1, 2, 3]))
[[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
"""
n = len(l)
for mask in range(2**n): yield [l[i-1] for i in range(1, n+1) if mask & (1 << (i-1))]
def primephi(x, a, ps, phicache={}): # TODO Mapes' method?
""" Legendre's phi function. Helper function for primepi. """
if (x, a) in phicache: return phicache[(x,a)]
if a == 1: return (x+1) // 2
phicache[(x,a)] = t = primephi(x, a-1, ps, phicache) - primephi(x // ps[a-1], a-1, ps, phicache)
return t
def primepi(x, ps=[], picache={}, phicache={}, sqrts={}):
"""
Number of primes <= x, computed using the Meissel-Lehmer method.
Input:
x -- an integer
ps -- a list of primes. This is for internal purposes only. Do not
pass values to it.
picache -- a cache of primepi values.
phicache -- a cache of primephi values.
sqrts -- a cache of square roots.
Passing data to the keyword arguments may improve performance;
however, this data is not checked for accuracy, and passing bad data
will probably yield bad results.
Output: An integer
Examples:
>>> list(map(primepi, [97, 542, 10**6, 2**27]))
[25, 100, 78498, 7603553]
"""
if x in picache: return picache[x]
if x <= 42:
picache[x] = t = len(list(primegen(x+1)))
return t
if x not in sqrts: sqrts[x] = isqrt(x)
if not ps:
ps, picache[0], picache[1], k = list(primegen(sqrts[x]+1)), 0, 0, 1
for (n,p) in enumerate(ps):
for k in range(k+1, p): picache[k] = n
for k in range(p, sqrts[x]+1): picache[k] = n+1
if sqrts[x] not in sqrts: sqrts[sqrts[x]] = isqrt(sqrts[x])
a, b, c = picache[sqrts[sqrts[x]]], picache[sqrts[x]], picache[introot(x,3)]
s = (b+a-2)*(b-a+1)//2 + primephi(x, a, ps, phicache)
for i in range(a+1, b+1):
w = x // ps[i-1]
if w not in sqrts: sqrts[w] = isqrt(w)
lim = picache[sqrts[w]]
s -= primepi(w, ps, picache, phicache, sqrts)
if i <= c:
s += (lim*(lim-1) - i*(i-3)) // 2 - 1
for j in range(i, lim+1): s -= picache[w//ps[j-1]]
picache[x] = s
return s
def primesum(n):
"""
Sum of primes <= n. Code shamelessly stolen from Lucy_Hedgehog's post
at https://projecteuler.net/thread=10;page=5.
Input: n -- integer
Output: An integer
Examples:
>>> [primesum(n) for n in (100, 1729, 10**6)]
[1060, 213538, 37550402023]
"""
r = isqrt(n)
V = [n//i for i in range(1,r+1)]
V += list(range(V[-1]-1,0,-1))
S = {i:i*(i+1)//2-1 for i in V}
for p in range(2,r+1):
if S[p] > S[p-1]: # p is prime
sp = S[p-1] # sum of primes smaller than p
p2 = p*p
for v in V:
if v < p2: break
S[v] -= p*(S[v//p] - sp)
return S[n]
def altseriesaccel(a, n):
"""
Convergence acceleration for alternating series. This is Algorithm 1
from the article "Convergence Acceleration of Alternating Series" by
Cohen, Villegas, and Zagier, with a minor tweak so that the d-value
is not computed via floating point. The article is available at
https://people.mpim-bonn.mpg.de/zagier/files/exp-math-9/fulltext.pdf.
Input:
a -- an iterable. The series to be summed is a[0] - a[1] + a[2] - ...
n -- the number of terms to use. A couple dozen terms is probably good.
Output: a floating-point number.
Examples:
""" # TODO
Vl, Vh = 2, 6
for bit in bin(n)[2:]: Vl, Vh = (Vh * Vl - 6, Vh * Vh - 2) if bit == '1' else (Vl * Vl - 2, Vh * Vl - 6)
d = Vl // 2
#d = (3 + sqrt(8))**n
#d = (d + 1/d) / 2
b, c, s = -1, -d, 0
for k in range(n):
c = b - c
s = s + c * next(a)
b = (k + n) * (k - n) * b / ((k + 0.5) * (k + 1))
return s / d
def riemannzeta(n, k=24): # TODO Use the functional equation for 0.5 < real(n) < 1.5. This requires a complex gamma function.
"""
The Riemann zeta function, computed by using a convergence-acceleration
technique (implemented as altseriesaccel) to the Dirichlet eta function.
Should be rather accurate throughout the complex plane except near n
such that 1 == 2**(n-1).
Input:
n -- point to evaluate at
k -- number of terms to use. Default == 24. Since we use
altseriesaccel, this is almost certainly sufficient.
Output:
A floating-point real number (if n is real) or a floating-point
complex number (if n is complex).
The pole at n == 1 manifests as a ZeroDivisionError.
Examples:
""" # TODO
return altseriesaccel((1/j**n for j in count(1)), k+1) / (1-2**(1-n))
def zetam1(n, k=24):
"""
Computes the Riemann zeta function minus 1 by applying a convergence-
acceleration technique (implemented as altseriesaccel) to the Dirichlet
eta function. Should converge for any complex n with positive real part
unless 1 == 2**(n-1), and accuracy may be low near such points.
Accurate even when riemannzeta(n) is machine-indistinguishable from 1.0:
in particular, when n is a large real number.
Input:
n -- point to evaluate at
k -- number of terms to use. Default == 24. Since we're using
altseriesaccel, this is almost certainly sufficient.
Output:
A floating-point real number (if n is real) or a floating-point
complex number (if n is complex).
The pole at n == 1 manifests as a ZeroDivisionError.
Examples:
"""
return (altseriesaccel((-1/j**n for j in count(2)), k+1) + 2**(1-n)) / (1-2**(1-n))
def riemannR(x, n=None, zc={}):
"""
Uses the Gram series to compute Riemann's R function, which is a very
good approximation to primepi.
Input:
x -- Integer. Evaluate the function at this point.
n -- Integer. Number of terms to use. Default == None; in this
case, we set n = 6 * int(log(x, 10)+1).
zc -- Dict. Default = {}. Keys are integers; values are the
Riemann zeta function at those integers. Erroneous values are
neither detected nor corrected. Unprovided values are
computed as needed.
Output: a floating-point real number.
Examples:
""" # TODO
if n is None: n = 6 * int(log(x, 10)+1) # TODO determine good default values for n
lnx = log(x)
total, lnxp, kfac = 0, 1, 1
for k in range(1, n+1):
lnxp *= lnx
kfac *= k
rz = zc.get(k+1, None)
if rz is None: rz = zc[k+1] = riemannzeta(k+1)
t = lnxp / (k * kfac * rz)
total += t
return 1+total
def nthprimeapprox(n):
"""
Produces an integer that should be rather close to the nth prime number
by using binary splitting on Riemann's R function.
Input: n -- an integer
Output: an integer
Examples:
""" # TODO
if n <= 2000:
if n < 26: return None if n < 1 else (0,2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97)[n]
ln_n = log(n)
lnln_n = log(ln_n)
return int(n * (ln_n + lnln_n - 1 + ( (lnln_n - 2) / ln_n )))
ln_n = log(n)
lnln_n = log(ln_n)
hi = ln_n + lnln_n
lo = hi - 1
x = lo + ( (lnln_n - 2) / ln_n )
lo, x, hi = int(lo * n), int(x * n), int(hi * n)
assert lo < x < hi
zc = {}
lo_g, x_g, hi_g = riemannR(lo, zc=zc), riemannR(x, zc=zc), riemannR(hi, zc=zc)
while lo != hi - 1:
x = (lo + hi) // 2
x_g = riemannR(x, zc=zc)
if x_g < n: lo = x
elif x_g > n: hi = x
else: return x
return lo
def nthprime(n):
"""
Returns the nth prime (counting 2 as #1)
Input: n -- an integer
Output: An integer
Examples:
>>> list(map(nthprime, (0, 1, 2, 3, 4, 25, 2**20)))
[None, 2, 3, 5, 7, 97, 16290047]
"""
if n < 1: return None
elif n <= 25:
ps = primegen()
for _ in range(n-1): next(ps)
return next(ps)
x = prevprime(nthprimeapprox(n))
c = primepi(x)
# x is prime and approximates the nth prime number.
# c is the number of primes <= x.
t = 0
while c > n: # TODO we can do better than this
x = prevprime(x)
c -= 1
t += 1
while c < n: # TODO we can do better than this
x = nextprime(x)
c += 1
t -= 1
return x
def gcd(a, *r): # TODO: When PyPy3 supports Python 3.9, replace with "from math import gcd".
"""
Greatest Common Divisor of a sequence of values.
Now that Python 3.9's math.gcd function supports arbitrary numbers of
arguments, a future version of this library will replace this function
definition with the line "from math import gcd". That will probably
happen when PyPy3 supports Python 3.9.
Input: integers (any number of them) or a single iterable of integers
Output: an integer
>>> x = (24, 42, 78, 93); (gcd(*x), gcd(x))
(3, 3)
>>> gcd(117, -17883411)
39
>>> gcd(3549, 70161, 336882, 702702)
273
"""
if not isinstance(a, inttypes): r = iter(a); a = next(r)
for b in r:
while b: a, b = b, a % b
return abs(a)
def xgcd(a, b): # TODO: this is ugly. Clean it up.
"""
Extended Euclidean algorithm: returns a tuple (g,x,y) where
g == gcd(a, b) and g == a*x + b*y.
Input: a, b -- integers
Output: Tuple of three integers
Examples:
>>> xgcd(42, 57)
(3, -4, 3)
>>> xgcd(1729, 98)
(7, -3, 53)
>>> xgcd(67, 71)
(1, -18, 17)
>>> xgcd(-20, 55)
(5, -3, -1)
"""
if a == 0 and b == 0: return (0, 0, 1)
if a == 0: return (abs(b), 0, b//abs(b))
if b == 0: return (abs(a), a//abs(a), 0)
x_sign = 1; y_sign = 1
if a < 0: a = -a; x_sign = -1
if b < 0: b = -b; y_sign = -1
x, y, r, s = 1, 0, 0, 1
while b != 0:
q = a//b
a, b, r, s, x, y = b, a%b, x-q*r, y-q*s, r, s
return (a, x*x_sign, y*y_sign)
def modinv(a, m): # TODO: Once PyPy3 supports Python 3.8, remove this in favor of pow(a, -1, m).
"""
Returns the inverse of a modulo m, normalized to lie between 0 and m-1.
If a is not coprime to m, return None.
DEPRECATION WARNING: as of version 3.8, this can be computed using
Python's built-in pow function as pow(a, -1, m). As such, a future
version of this library will remove this function. That will probably
happen once PyPy3 supports Python 3.8.
Input:
a -- an integer coprime to m
n -- a positive integer
Output: None, or an integer x between 0 and m-1 such that (a*x) % m == 1
Examples:
>>> [modinv(1,1), modinv(2,5), modinv(5,8), modinv(37,100), modinv(6,8)]
[0, 3, 5, 73, None]
"""
if m <= 0: return None
M, x, r = m, 1, 0
while m != 0:
q = a//m
a, m, r, x = m, a%m, x-q*r, r
return x % M if a == 1 else None
def crt(rems, mods): # moduli and remainders are lists; moduli must be pairwsise coprime.
"""
Return the unique integer in range(iterprod(mods)) that reduces to x % y
for (x,y) in zip(rems,mods). All elements of mods must be pairwise
coprime.
Input: rems, mods -- iterables of the same finite length containing integers
Output: an integer in range(iterprod(mods))
Examples:
>>> crt((1, 2), (3, 4))
10
>>> crt((4, 5), (10, 3))
14
>>> crt((-1, -1), (100, 101))
10099
"""
if len(mods) == 1: return rems[0]
N = iterprod(mods)
return sum(r * (N//m) * modinv(N//m, m) for (r, m) in zip(rems, mods) if m != 1) % N
def lcm(a, *r): # TODO: When PyPy3 supports Python 3.9, replace this with "from math import lcm".
"""
The least common multiple of the inputs.
Now that Python 3.9 has the math.lcm function, a future version of this
library will remove this function definition in favor of the line
"from math import lcm". That will probably happen when PyPy3 supports
Python 3.9.
Input: integers (any number of them) or a single iterable of integers.
Output: An integer
Examples:
>>> lcm(10, 15)
30
>>> lcm(42, 57)
798
>>> lcm(1701, 13979)
3396897
>>> lcm(117, -17883411)
53650233
>>> lcm(3549, 70161, 336882, 702702)
111426753438
>>> lcm(range(1, 10))
2520
"""
if not isinstance(a, inttypes): a, r = 1, a
for b in r: a *= b // gcd(a, b)
return abs(a)
def isqrt(n): # TODO: When PyPy3 supports Python 3.9, replace this with "from math import isqrt".
"""
Greatest integer less than or equal to the square root of n.
Shamelessly stolen from https://codegolf.stackexchange.com/a/9088.
Now that Python 3.9 has the math.isqrt function, a future version of
this library will remove this function definition in favor of the line
"from math import isqrt". That will probably happen when PyPy3 supports
Python 3.9.
Input: n -- a whole number
Output: An integer
Examples:
>>> list(map(isqrt, range(24)))
[0, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4]
"""
if n < 0: return int(n)
c = n*4//3
d = c.bit_length()
a = d>>1
if d&1:
x = 1 << a
y = (x + (n >> a)) >> 1
else:
x = (3 << a) >> 2
y = (x + (c >> a)) >> 1
if x != y:
x, y = y, (y + n//y) >> 1
while y < x: x, y = y, (y + n//y) >> 1
return x
def introot(n, r=2): # TODO Newton iteration?
"""
Returns the rth root of n, rounded to the nearest integer in the
direction of zero. Returns None if r is even and n is negative.
Input:
n -- an integer
r -- a natural number or None
Output: An integer
Examples:
>>> [introot(-729, 3), introot(-728, 3)]
[-9, -8]
>>> [introot(1023, 2), introot(1024, 2)]
[31, 32]
"""
if n < 0: return None if r%2 == 0 else -introot(-n, r)
if n < 2: return n
if r == 1: return n
if r == 2: return isqrt(n)
#if r % 2 == 0: return introot(isqrt(n), r//2) # TODO Check validity of this line.
lower = upper = 1 << (n.bit_length() // r)
while lower ** r > n: lower >>= 2
while upper ** r <= n: upper <<= 2
while lower != upper - 1:
mid = (lower + upper) // 2
m = mid**r
if m == n: return mid
elif m < n: lower = mid
elif m > n: upper = mid
return lower
def ispower(n, r=0):
"""
Checks whether n is a perfect power.
If r == 0:
If n is a perfect power, return a tuple containing largest integer
(in terms of magnitude) that, when squared/cubed/etc, yields n as
the first component and the relevant power as the second component.
If n is not a perfect power, return None.
If r > 0:
We check whether n is a perfect rth power; we return its rth root if
it is and None if it isn't.
Input:
n -- an integer
r -- an integer
Output: An integer, a 2-tuple of integers, or None
Examples:
>>> [ispower(n) for n in [64, 25, -729, 1729]]
[(8, 2), (5, 2), (-9, 3), None]
>>> [ispower(64, r) for r in range(7)]
[(8, 2), 64, 8, 4, None, None, 2]
"""
#if r == 0: return any(ispower(n, r) for r in primegen(n.bit_length()+1))
#return n == introot(n, r) ** r
if r == 0:
if n in (0, 1, -1): return (n, 1)
for r in primegen(n.bit_length()+1):
x = ispower(n, r)
if x is not None: return (x, r)
return None
# TODO tricks for special cases
if (r == 2) and (n & 2): return None
if (r == 3) and (n & 7) in (2,4,6): return None
x = introot(n, r)
return None if x is None else (x if x**r == n else None)
def ilog(x, b): # TODO: investigate optimization starting from x.bin_length() * 2 // b
"""
Greatest integer l such that b**l <= x
Input: x, b -- integers
Output: An integer
Examples:
>>> ilog(263789, 10)
5
>>> ilog(1023, 2)
9
"""
l = 0
while x >= b:
x //= b
l += 1
return l
# TODO possible optimization route: x.bit_length() == ilog(x, 2) + 1; we can therefore use x.bit_length() * 2 // b as a
# 1st approximation to ilog(x, b), then compute pow(b, x.bit_length() * 2 // b), then compare that to x and adjust.
def semiprimegen():
"""
Generates the semiprimes, by filtering the primes out of the output of
pspgen.
Input: none.
Output: infinite sequence of integers
Examples:
>>> list(islice(semiprimegen(), 19))
[4, 6, 9, 10, 14, 15, 21, 22, 25, 26, 33, 34, 35, 38, 39, 46, 49, 51, 55]
"""
pg, pspg = primegen(), pspgen()
p, psp = next(pg), next(pspg)
while True:
if p == psp: p, psp = next(pg), next(pspg)
else: yield psp; psp = next(pspg)
def pspgen(): # TODO: implement an upper bound as in primegen.
"""
Generates the primes and semiprimes, using a segmented sieve based on the
sieve of Eratosthenes and the fact that these are precisely the numbers not
divisible by any smaller semiprimes.
Input: none
Output: infinite sequence of integers
Examples:
>>> list(islice(pspgen(), 20))
[2, 3, 4, 5, 6, 7, 9, 10, 11, 13, 14, 15, 17, 19, 21, 22, 23, 25, 26, 29]
"""
yield from (2,3,4,5,6,7,9,10,11,13,14,15,17,19,21,22,23,25,26,29,31,33,34,35,37,38,39,41,43,46,47,49,51)
low = 52
length = 7**3 - 52 # == 293
end = low + length # == 343
maxsp = introot(end**2, 3) + 1 # == 50
spg = semiprimegen()
spl = [next(spg) for _ in range(16)] # == [4,6,9,10,14,15,21,22,25,26,33,34,35,38,39,46,49]
nextsp = next(spg)
while True:
sieve = bytearray([True]) * length
for sp in spl:
n = (-low) % sp
while n < length:
sieve[n] = False
n += sp
#sieve[n::sp] = bytearray([False]) * ((length-n-1)//sp + 1)
for n in range(length):
if sieve[n]: yield n + low
low += length
length = len(spl)
end = low + length
maxsp = introot(end**2, 3) + 1
while nextsp < maxsp:
spl.append(nextsp)
nextsp = next(spg)
def almostprimegen(k):
"""
Generates the k-almost-primes, which are the numbers that have precisely k
prime factors, counted with multiplicity. This is done by filtering
nearlyprimegen(k-1) out of the output of nearlyprimegen(k).
Input: k -- an integer
Output: infinite sequence of integers
Examples:
>>> list(islice(almostprimegen(3), 19))
[8, 12, 18, 20, 27, 28, 30, 42, 44, 45, 50, 52, 63, 66, 68, 70, 75, 76, 78]
>>> list(islice(almostprimegen(4), 17))
[16, 24, 36, 40, 54, 56, 60, 81, 84, 88, 90, 100, 104, 126, 132, 135, 136]
"""
# A number is called a k-almost-prime if it has exactly k prime factors, counted with multiplicity.
# We proceed by generating the k-nearly-primes and (k-1)-nearly-primes, and filtering the (k-1)-nps out of the k-nps.
if k == 1:
yield from primegen()
return
km1_npgen, k_npgen = nearlyprimegen(k-1), nearlyprimegen(k)
km1_np, k_np = next(km1_npgen), next(k_npgen)
while True:
if km1_np == k_np: km1_np, k_np = next(km1_npgen), next(k_npgen)
else: yield k_np; k_np = next(k_npgen)
def nearlyprimegen(k):
"""
Generates the numbers (other than 1) that have k or fewer prime factors,
counted with multipicity. This is done via a segmented sieve based on the
sieve of Eratosthenes and the fact that these are precisely the numbers not
divisible by any smaller k-almost-primes.
Input: k -- an integer
Output: infinite sequence of integers
Examples:
>>> list(islice(nearlyprimegen(3), 35))
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 28, 29, 30, 31, 33, 34, 35, 37, 38, 39, 41]
"""
# This generates the numbers that have 1, 2, 3, ..., or k prime factors, counted with multiplicity.
if k == 1:
yield from primegen()
return
if k == 2:
yield from pspgen()
return
assert k >= 3
# The first number that is not a k-nearly-prime is 2**(k+1).
yield from range(2, 2**(k+1))
# All numbers strictly between 2**(k+1) and 9 * 2**(k-2) have Omega < k.
# 9 * 2**(k-2) is the first number > 2**(k+1) (and third overall) with Omega == k.
yield from range(2**(k+1) + 1, 9 * 2**(k-2) + 1)
# The k-nearly-primes are precisely the numbers that are not divisible by any smaller k-almost-primes.
kapgen = almostprimegen(k)
low = 9 * 2**(k-2) + 1 # This variable holds the number that is at the bottom end of the sieving interval.
# To sieve out to x, we need to store the k-almost-primes up to x**(k/(k+1)).
# Equivalently, if we have the k-almost-primes up to x, then we can sieve out to x**((k+1)/k).
end = introot(low**(k+1), k)
length = end - low
maxkap = 2**(k+1) + 1 #introot(end**k, k+1) + 1
kaplist = []
while True:
nextkap = next(kapgen)
if nextkap < maxkap: kaplist.append(nextkap)
else: break
while True:
sieve = bytearray([True]) * length
for kap in kaplist:
n = (-low) % kap
while n < length:
sieve[n] = False
n += kap
#sieve[n::kap] = bytearray([False]) * ((length-n-1)//kap + 1)
for n in range(length):
if sieve[n]: yield n + low
low += length
length = len(kaplist)
end = low + length
maxkap = introot(end**k, k+1) + 1
while nextkap < maxkap:
kaplist.append(nextkap)
nextkap = next(kapgen)
def fibogen():
"""
Generates the Fibonacci numbers, starting with 0 and 1.
Input: none
Output: Sequence of integers
Examples:
>>> list(islice(fibogen(), 12))
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
"""
a, b = 0, 1
while True: yield a; a, b = b, a+b
def fibo(n, f={0:0, 1:1, 2:1}): # TODO iterative version
"""
Efficiently extracts the nth Fibonacci number, indexed so that
fibo(0) == 0 and fibo(1) == fibo(2) == 1. Computes O(log(n)) earlier
Fibonaccis along the way. This is, in the big-O sense, just about as
fast as possible.
Input:
n -- non-negative integer
f -- dict of Fibonacci numbers. Used for memoization purposes.
Output: An integer
Examples:
>>> fibo(346)
912511873855702065852730553217787283194150290277873860991322859307033303
>>> x = fibo(100000); (x // 10**20879, x % 10**20)
(25974069347221724166, 49895374653428746875)
"""
if n in f: return f[n]
if n % 2: f[n] = fibo(n//2 + 1 , f) ** 2 + fibo(n//2 , f) ** 2
else: f[n] = fibo(n//2 + 1 , f) ** 2 - fibo(n//2 - 1 , f) ** 2
return f[n]
def fibomod(n, m, f={0:0, 1:1, 2:1}): # TODO iterative version. What is up with the caching weirdness?
"""
Efficiently extracts the nth Fibonacci number, indexed so that
fibo(0) == 0 and fibo(1) == fibo(2) == 1, mod m. Computes O(log(n))
earlier Fibonaccis along the way. This is, in the big-O sense, just
about as fast as possible.
Input:
n -- non-negative integer
m -- positive integer
f -- dict of Fibonacci numbers. Used for memoization.
Output: An integer
Examples:
>>> fibomod(512, 73)
8
>>> fibomod(100000, 10**20)
49895374653428746875
"""
if m == 1: return 0
if n in f: return f[n]
if n % 2: f[n] = ( fibomod(n//2 + 1, m, f) ** 2 + fibomod(n//2 , m, f) ** 2 ) % m
else: f[n] = ( fibomod(n//2 + 1, m, f) ** 2 - fibomod(n//2 - 1, m, f) ** 2 ) % m
return f[n]
def lucaschain(n, x0, x1, op1, op2):
"""
Algorithm 3.6.7 from Crandall & Pomerance 2005 (page 147): evaluation of
a binary Lucas chain. To quote their description:
For a sequence x0, x1, ... with a rule for computing x_2j from x_j and a
rule for computing x_(2j+1) from x_j and x_(j+1), this algorithm
computes (x_n, x_(n+1)) for a given positive integer n. We have n in
binary as (n0, n1, ..., n_(b-1)) with n0 being the low-order bit. We
write the rules as follows: x_2j = op1(x_j) and
x_(2j+1) = op2(x_j, x_(j+1)). At each step in the for loop we have
u = x_j, v = x_(j+1) for some nonnegative integer j.
Input:
n -- positive integer
x0, x1 -- numbers
op1, op2 -- functions. op1 takes one argument; op2 takes two.
Output: 2-tuple of numbers
Examples: