-
Notifications
You must be signed in to change notification settings - Fork 6
/
math2.py
2742 lines (2151 loc) · 75.1 KB
/
math2.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 python
# coding: utf8
'''
more math than :mod:`math` standard library, without numpy
'''
__author__ = "Philippe Guglielmetti"
__copyright__ = "Copyright 2012, Philippe Guglielmetti"
__credits__ = [
"https://pypi.python.org/pypi/primefac"
"https://github.com/tokland/pyeuler/blob/master/pyeuler/toolset.py",
"http://blog.dreamshire.com/common-functions-routines-project-euler/",
]
__license__ = "LGPL"
import logging
import math, cmath, operator, itertools, functools, fractions, numbers, random
from Goulib import itertools2, decorators
inf = float('Inf') # infinity
eps = 2.2204460492503131e-16 # numpy.finfo(np.float64).eps
try:
nan = math.nan
except:
nan = float('nan') # Not a Number
def cmp(x, y):
'''Compare the two objects x and y and return an integer according to the outcome.
The return value is negative if x < y, zero if x == y and strictly positive if x > y.
'''
return sign(x - y)
try:
isclose = math.isclose
except AttributeError:
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
'''approximately equal. Use this instead of a==b in floating point ops
implements https://www.python.org/dev/peps/pep-0485/
:param a,b: the two values to be tested to relative closeness
:param rel_tol: relative tolerance
it is the amount of error allowed, relative to the larger absolute value of a or b.
For example, to set a tolerance of 5%, pass tol=0.05.
The default tolerance is 1e-9, which assures that the two values are the same within
about 9 decimal digits. rel_tol must be greater than 0.0
:param abs_tol: minimum absolute tolerance level -- useful for comparisons near zero.
'''
# https://github.com/PythonCHB/close_pep/blob/master/isclose.py
if a == b: # short-circuit exact equality
return True
if rel_tol < 0.0 or abs_tol < 0.0:
raise ValueError('error tolerances must be non-negative')
# use cmath so it will work with complex ot float
if math.isinf(abs(a)) or math.isinf(abs(b)):
# This includes the case of two infinities of opposite sign, or
# one infinity and one finite number. Two infinities of opposite sign
# would otherwise have an infinite relative tolerance.
return False
diff = abs(b - a)
return (((diff <= abs(rel_tol * b)) or
(diff <= abs(rel_tol * a))) or
(diff <= abs_tol))
def allclose(a, b, rel_tol=1e-09, abs_tol=0.0):
''':return: True if two arrays are element-wise equal within a tolerance.'''
# https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.allclose.html
for x, y in itertools.zip_longest(a, b):
if x is None or y is None:
return False
if not isclose(x, y, rel_tol=rel_tol, abs_tol=abs_tol):
return False
return True
# basic useful functions
def is_number(x):
''':return: True if x is a number of any type, including Complex'''
# http://stackoverflow.com/questions/4187185/how-can-i-check-if-my-python-object-is-a-number
return isinstance(x, numbers.Number)
def is_complex(x):
return isinstance(x, complex)
def is_real(x):
return is_number(x) and not is_complex(x)
def sign(number):
''':return: 1 if number is positive, -1 if negative, 0 if ==0'''
if number < 0:
return -1
if number > 0:
return 1
return 0
# rounding
def rint(v):
'''
:return: int value nearest to float v
'''
return int(round(v))
def is_integer(x, rel_tol=0, abs_tol=0):
'''
:return: True if float x is an integer within tolerances
'''
if isinstance(x, int):
return True
try:
if rel_tol + abs_tol == 0:
return x == rint(x)
return isclose(x, round(x), rel_tol=rel_tol, abs_tol=abs_tol)
except TypeError: # for complex
return False
def int_or_float(x, rel_tol=0, abs_tol=0):
'''
:param x: int or float
:return: int if x is (almost) an integer, otherwise float
'''
return rint(x) if is_integer(x, rel_tol, abs_tol) else x
def format(x, decimals=3):
''' formats a float with given number of decimals, but not an int
:return: string repr of x with decimals if not int
'''
if is_integer(x):
decimals = 0
return '{0:.{1}f}'.format(x, decimals)
# improved versions of math functions
def gcd(*args):
'''greatest common divisor of an arbitrary number of args'''
# http://code.activestate.com/recipes/577512-gcd-of-an-arbitrary-list/
L = list(args) # in case args are generated
b = L[0] # will be returned if only one arg
while len(L) > 1:
a = L[-2]
b = L[-1]
L = L[:-2]
while a:
a, b = b % a, a
L.append(b)
return abs(b)
def lcm(*args):
'''least common multiple of any number of integers'''
if len(args) <= 2:
return mul(args) // gcd(*args)
# TODO : better
res = lcm(args[0], args[1])
for n in args[2:]:
res = lcm(res, n)
return res
def xgcd(a, b):
'''Extended GCD
:return: (gcd, x, y) where gcd is the greatest common divisor of a and b
with the sign of b if b is nonzero, and with the sign of a if b is 0.
The numbers x,y are such that gcd = ax+by.'''
# taken from http://anh.cs.luc.edu/331/code/xgcd.py
prevx, x = 1, 0;
prevy, y = 0, 1
while b:
q, r = divmod(a, b)
x, prevx = prevx - q * x, x
y, prevy = prevy - q * y, y
a, b = b, r
return a, prevx, prevy
def coprime(*args):
''':return: True if args are coprime to each other'''
return gcd(*args) == 1
def coprimes_gen(limit):
'''generates coprime pairs
using Farey sequence
'''
# https://www.quora.com/What-are-the-fastest-algorithms-for-generating-coprime-pairs
pend = []
n, d = 0, 1 # n, d is the start fraction n/d (0,1) initially
N = D = 1 # N, D is the stop fraction N/D (1,1) initially
while True:
mediant_d = d + D
if mediant_d <= limit:
mediant_n = n + N
pend.append((mediant_n, mediant_d, N, D))
N = mediant_n
D = mediant_d
else:
yield n, d # numerator / denominator
if pend:
n, d, N, D = pend.pop()
else:
break
def carmichael(n):
'''
Carmichael function
:return : int smallest positive integer m such that a^m mod n = 1 for every integer a between 1 and n that is coprime to n.
:param n: int
:see: https://en.wikipedia.org/wiki/Carmichael_function
:see: https://oeis.org/A002322
also known as the reduced totient function or the least universal exponent function.
'''
coprimes = [x for x in range(1, n) if gcd(x, n) == 1]
k = 1
while not all(pow(x, k, n) == 1 for x in coprimes):
k += 1
return k
# https://en.wikipedia.org/wiki/Primitive_root_modulo_n
# code decomposed from http://stackoverflow.com/questions/40190849/efficient-finding-primitive-roots-modulo-n-using-python
def is_primitive_root(x, m, s={}):
'''returns True if x is a primitive root of m
:param s: set of coprimes to m, if already known
'''
if not s:
s = {n for n in range(1, m) if coprime(n, m)}
return {pow(x, p, m) for p in range(1, m)} == s
def primitive_root_gen(m):
'''generate primitive roots modulo m'''
required_set = {num for num in range(1, m) if coprime(num, m)}
for n in range(1, m):
if is_primitive_root(n, m, required_set):
yield n
def primitive_roots(modulo):
return list(primitive_root_gen(modulo))
def quad(a, b, c, allow_complex=False):
''' solves quadratic equations aX^2+bX+c=0
:param a,b,c: floats
:param allow_complex: function returns complex roots if True
:return: x1,x2 real or complex solutions
'''
discriminant = b * b - 4 * a * c
if allow_complex:
d = cmath.sqrt(discriminant)
else:
d = math.sqrt(discriminant)
return (-b + d) / (2 * a), (-b - d) / (2 * a)
def ceildiv(a, b):
return -(-a // b) # simple and clever
def ipow(x, y, z=0):
'''
:param x: number (int or float)
:param y: int power
:param z: int optional modulus
:return: (x**y) % z as integer if possible
'''
if y < 0:
if z:
raise NotImplementedError('no modulus allowed for negative power')
else:
return 1 / ipow(x, -y)
a, b = 1, x
while y > 0:
if y % 2 == 1:
a = (a * b) % z if z else a * b
b = (b * b) % z if z else b * b
y = y // 2
return a
def pow(x, y, z=0):
'''
:return: (x**y) % z as integer
'''
if not isinstance(y, int):
if z == 0:
return pow(x, y) # switches to floats in Py3...
else:
return pow(x, y, z) # switches to floats in Py3...
else:
return ipow(x, y, z)
def sqrt(n):
'''square root
:return: int, float or complex depending on n
'''
if type(n) is int:
s = isqrt(n)
if s * s == n:
return s
if n < 0:
return cmath.sqrt(n)
return math.sqrt(n)
def isqrt(n):
'''integer square root
:return: largest int x for which x * x <= n
'''
# http://stackoverflow.com/questions/15390807/integer-square-root-in-python
# https://projecteuler.net/thread=549#235536
n = int(n)
x = n
y = (x + 1) // 2
while y < x:
x = y
y = (x + n // x) // 2
return x
def icbrt(n):
'''integer cubic root
:return: largest int x for which x * x * x <= n
'''
# https://projecteuler.net/thread=549#235536
if n <= 0:
return 0
x = int(n ** (1. / 3.) * (1 + 1e-12))
while True:
y = (2 * x + n // (x * x)) // 3
if y >= x:
return x
x = y
def is_square(n):
s = isqrt(n)
return s * s == n
def introot(n, r=2):
''' integer r-th root
:return: int, greatest integer less than or equal to the r-th root of n.
For negative n, returns the least integer greater than or equal to the r-th root of n, or None if r is even.
'''
# copied from https://pypi.python.org/pypi/primefac
if n < 0: return None if r % 2 == 0 else -introot(-n, r)
if n < 2: return n
if r == 2: return isqrt(n)
lower, upper = 0, n
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 is_power(n):
'''
:return: integer that, when squared/cubed/etc, yields n,
or 0 if no such integer exists.
Note that the power to which this number is raised will be prime.'''
# copied from https://pypi.python.org/pypi/primefac
for p in primes_gen():
r = introot(n, p)
if r is None: continue
if r ** p == n: return r
if r == 1: return 0
def multiply(x, y):
'''
Karatsuba fast multiplication algorithm
https://en.wikipedia.org/wiki/Karatsuba_algorithm
Copyright (c) 2014 Project Nayuki
http://www.nayuki.io/page/karatsuba-multiplication
'''
_CUTOFF = 1536 # _CUTOFF >= 64, or else there will be infinite recursion.
if x.bit_length() <= _CUTOFF or y.bit_length() <= _CUTOFF: # Base case
return x * y
else:
n = max(x.bit_length(), y.bit_length())
half = (n + 32) // 64 * 32
mask = (1 << half) - 1
xlow = x & mask
ylow = y & mask
xhigh = x >> half
yhigh = y >> half
a = multiply(xhigh, yhigh)
b = multiply(xlow + xhigh, ylow + yhigh)
c = multiply(xlow, ylow)
d = b - a - c
return (((a << half) + d) << half) + c
# vector operations
def accsum(it):
'''Yield accumulated sums of iterable: accsum(count(1)) -> 1,3,6,10,...'''
return itertools2.drop(1, itertools2.ireduce(operator.add, it, 0))
cumsum = accsum # numpy alias
def mul(nums, init=1):
'''
:return: Product of nums
'''
return functools.reduce(operator.mul, nums, init)
def dot_vv(a, b, default=0):
'''dot product for vectors
:param a: vector (iterable)
:param b: vector (iterable)
:param default: default value of the multiplication operator
'''
return sum(map(operator.mul, a, b), default)
def dot_mv(a, b, default=0):
'''dot product for vectors
:param a: matrix (iterable or iterables)
:param b: vector (iterable)
:param default: default value of the multiplication operator
'''
return [dot_vv(line, b, default) for line in a]
def dot_mm(a, b, default=0):
'''dot product for matrices
:param a: matrix (iterable or iterables)
:param b: matrix (iterable or iterables)
:param default: default value of the multiplication operator
'''
return transpose([dot_mv(a, col) for col in zip(*b)])
def dot(a, b, default=0):
'''dot product
general but slow : use dot_vv, dot_mv or dot_mm if you know a and b's dimensions
'''
if itertools2.ndim(a) == 2: # matrix
if itertools2.ndim(b) == 2: # matrix*matrix
return dot_mm(a, b, default)
else: # matrix*vector
return dot_mv(a, b, default)
else: # vector*vector
return dot_vv(a, b, default)
# some basic matrix ops
def zeros(shape):
'''
:see: https://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html
'''
return ([0] * shape[1]) * shape[0]
def diag(v):
'''
Create a two-dimensional array with the flattened input as a diagonal.
:param v: If v is a 2-D array, return a copy of its diagonal.
If v is a 1-D array, return a 2-D array with v on the diagonal
:see: https://docs.scipy.org/doc/numpy/reference/generated/numpy.diag.html#numpy.diag
'''
s = len(v)
if itertools2.ndim(v) == 2:
return [v[i][i] for i in range(s)]
res = []
for i, x in enumerate(v):
line = [x] + [0] * (s - 1)
line = line[-i:] + line[:-i]
res.append(line)
return res
def identity(n):
return diag([1] * n)
eye = identity # alias for now
def transpose(m):
'''
:return: matrix m transposed
'''
# ensures the result is a list of lists
return list(map(list, list(zip(*m))))
def maximum(m):
'''
Compare N arrays and returns a new array containing the element-wise maxima
:param m: list of arrays (matrix)
:return: list of maximal values found in each column of m
:see: http://docs.scipy.org/doc/numpy/reference/generated/numpy.maximum.html
'''
return [max(c) for c in transpose(m)]
def minimum(m):
'''
Compare N arrays and returns a new array containing the element-wise minima
:param m: list of arrays (matrix)
:return: list of minimal values found in each column of m
:see: http://docs.scipy.org/doc/numpy/reference/generated/numpy.minimum.html
'''
return [min(c) for c in transpose(m)]
def vecadd(a, b, fillvalue=0):
'''addition of vectors of inequal lengths'''
return [l[0] + l[1] for l in itertools.zip_longest(a, b, fillvalue=fillvalue)]
def vecsub(a, b, fillvalue=0):
'''substraction of vectors of inequal lengths'''
return [l[0] - l[1] for l in itertools.zip_longest(a, b, fillvalue=fillvalue)]
def vecneg(a):
'''unary negation'''
return list(map(operator.neg, a))
def vecmul(a, b):
'''product of vectors of inequal lengths'''
if isinstance(a, (int, float)):
return [x * a for x in b]
if isinstance(b, (int, float)):
return [x * b for x in a]
return [functools.reduce(operator.mul, l) for l in zip(a, b)]
def vecdiv(a, b):
'''quotient of vectors of inequal lengths'''
if isinstance(b, (int, float)):
return [float(x) / b for x in a]
return [functools.reduce(operator.truediv, l) for l in zip(a, b)]
def veccompare(a, b):
'''compare values in 2 lists. returns triple number of pairs where [a<b, a==b, a>b]'''
res = [0, 0, 0]
for ai, bi in zip(a, b):
if ai < bi:
res[0] += 1
elif ai == bi:
res[1] += 1
else:
res[2] += 1
return res
def sat(x, low=0, high=None):
''' saturates x between low and high '''
if isinstance(x, (int, float)):
if low is not None: x = max(x, low)
if high is not None: x = min(x, high)
return x
return [sat(_, low, high) for _ in x]
# norms and distances
def norm_2(v):
'''
:return: "normal" euclidian norm of vector v
'''
return sqrt(sum(x * x for x in v))
def norm_1(v):
'''
:return: "manhattan" norm of vector v
'''
return sum(abs(x) for x in v)
def norm_inf(v):
'''
:return: infinite norm of vector v
'''
return max(abs(x) for x in v)
def norm(v, order=2):
'''
:see: http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.norm.html
'''
return sum(abs(x) ** order for x in v) ** (1. / order)
def dist(a, b, norm=norm_2):
return norm(vecsub(a, b))
def vecunit(v, norm=norm_2):
'''
:return: vector normalized
'''
return vecdiv(v, norm(v))
def hamming(s1, s2):
'''Calculate the Hamming distance between two iterables'''
return sum(c1 != c2 for c1, c2 in zip(s1, s2))
def sets_dist(a, b):
'''
:see: http://stackoverflow.com/questions/11316539/calculating-the-distance-between-two-unordered-sets
'''
c = a.intersection(b)
return sqrt(len(a - c) * 2 + len(b - c) * 2)
def sets_levenshtein(a, b):
'''levenshtein distance on sets
:see: http://en.wikipedia.org/wiki/Levenshtein_distance
'''
c = a.intersection(b)
return len(a - c) + len(b - c)
def levenshtein(seq1, seq2):
'''levenshtein distance
:return: distance between 2 iterables
:see: http://en.wikipedia.org/wiki/Levenshtein_distance
'''
# http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Python
oneago = None
thisrow = list(range(1, len(seq2) + 1)) + [0]
for x in range(len(seq1)):
_, oneago, thisrow = oneago, thisrow, [0] * len(seq2) + [x + 1]
for y in range(len(seq2)):
delcost = oneago[y] + 1
addcost = thisrow[y - 1] + 1
subcost = oneago[y - 1] + (seq1[x] != seq2[y])
thisrow[y] = min(delcost, addcost, subcost)
return thisrow[len(seq2) - 1]
# stats
# moved to stats.py
# numbers functions
# mostly from https://github.com/tokland/pyeuler/blob/master/pyeuler/toolset.py
def recurrence(signature, values, cst=0, max=None, mod=0):
'''general generator for recurrences
:param signature: factors defining the recurrence
:param values: list of initial values
'''
values = list(values) # to allow tuples or iterators
factors = list(reversed(signature))
for n in values:
if mod:
n = n % mod
yield n
values = values[-len(signature):]
while True:
n = dot_vv(factors, values)
if max and n > max: break
n = n + cst
if mod: n = n % mod
yield n
values = values[1:]
values.append(n)
def kfibonacci_gen(k, init=None, max=None, mod=0):
'''Generate k-fibonacci serie'''
init = init or [0] * (k - 1) + [1]
return recurrence([1] * k, init, max=max, mod=mod)
def fibonacci_gen(max=None, mod=0):
'''Generate fibonacci serie (k=2)'''
return kfibonacci_gen(2, None, max, mod)
def kfibonacci(k, mod=0):
''' k-fibonacci series n-th element
:param k: int number of consecutive terms to add
:param mod: int optional modulo
:return: function(n) returning the n-th element
'''
# http://stackoverflow.com/a/28549402/1395973
# uses http://mathworld.wolfram.com/FibonacciQ-Matrix.html
mat = identity(k - 1)
for row in mat:
row.append(0)
mat.insert(0, [1] * k)
return lambda n:mod_matpow(mat, n, mod)[0][k - 1]
def fibonacci(n, mod=0):
''' fibonacci series n-th element
:param n: int can be extremely high, like 1e19 !
:param mod: int optional modulo
'''
return kfibonacci(2, mod)(n)
def is_fibonacci(n):
'''returns True if n is in Fibonacci series'''
# http://www.geeksforgeeks.org/check-number-fibonacci-number/
return is_square(5 * n * n + 4) or is_square(5 * n * n - 4)
def pisano_cycle(mod):
if mod < 2: return [0]
seq = [0, 1]
l = len(seq)
s = []
for i, n in enumerate(fibonacci_gen(mod=mod)):
s.append(n)
if i > l and s[-l:] == seq:
return s[:-l]
def pisano_period(mod):
if mod < 2: return 1
flag = False # 0 was found
for i, n in enumerate(fibonacci_gen(mod=mod)):
if not flag:
flag = n == 0
elif i > 3:
if n == 1:
return i - 1
flag = False
def collatz(n):
if n % 2 == 0:
return n // 2
else:
return 3 * n + 1
def collatz_gen(n=0):
yield n
while True:
n = collatz(n)
yield n
@decorators.memoize
def collatz_period(n):
if n == 1: return 1
return 1 + collatz_period(collatz(n))
def pascal_gen():
'''Pascal's triangle read by rows: C(n,k) = binomial(n,k) = n!/(k!*(n-k)!), 0<=k<=n.
https://oeis.org/A007318
'''
__author__ = 'Nick Hobson <nickh@qbyte.org>'
# code from https://oeis.org/A007318/a007318.py.txt with additional related functions
for row in itertools.count():
x = 1
yield x
for m in range(row):
x = (x * (row - m)) // (m + 1)
yield x
def catalan(n):
'''Catalan numbers: C(n) = binomial(2n,n)/(n+1) = (2n)!/(n!(n+1)!).
'''
return binomial(2 * n, n) // (n + 1) # result is always int
def catalan_gen():
'''Generate Catalan numbers: C(n) = binomial(2n,n)/(n+1) = (2n)!/(n!(n+1)!).
Also called Segner numbers.
'''
yield 1
last = 1
yield last
for n in itertools.count(1):
last = last * (4 * n + 2) // (n + 2)
yield last
def is_pythagorean_triple(a, b, c):
return a * a + b * b == c * c
def primitive_triples():
''' generates primitive Pythagorean triplets x<y<z
sorted by hypotenuse z, then longest side y
through Berggren's matrices and breadth first traversal of ternary tree
:see: https://en.wikipedia.org/wiki/Tree_of_primitive_Pythagorean_triples
'''
key = lambda x: (x[2], x[1])
from sortedcontainers import SortedListWithKey
triples = SortedListWithKey(key=key)
triples.add([3, 4, 5])
A = [[1, -2, 2], [2, -1, 2], [2, -2, 3]]
B = [[1, 2, 2], [2, 1, 2], [2, 2, 3]]
C = [[-1, 2, 2], [-2, 1, 2], [-2, 2, 3]]
while triples:
(a, b, c) = triples.pop(0)
yield (a, b, c)
# expand this triple to 3 new triples using Berggren's matrices
for X in [A, B, C]:
triple = [sum(x * y for (x, y) in zip([a, b, c], X[i])) for i in range(3)]
if triple[0] > triple[1]: # ensure x<y<z
triple[0], triple[1] = triple[1], triple[0]
triples.add(triple)
def triples():
''' generates all Pythagorean triplets triplets x<y<z
sorted by hypotenuse z, then longest side y
'''
prim = [] # list of primitive triples up to now
key = lambda x: (x[2], x[1])
from sortedcontainers import SortedListWithKey
samez = SortedListWithKey(key=key) # temp triplets with same z
buffer = SortedListWithKey(key=key) # temp for triplets with smaller z
for pt in primitive_triples():
z = pt[2]
if samez and z != samez[0][2]: # flush samez
while samez:
yield samez.pop(0)
samez.add(pt)
# build buffer of smaller multiples of the primitives already found
for i, pm in enumerate(prim):
p, m = pm[0:2]
while True:
mz = m * p[2]
if mz < z:
buffer.add(tuple(m * x for x in p))
elif mz == z:
# we need another buffer because next pt might have
# the same z as the previous one, but a smaller y than
# a multiple of a previous pt ...
samez.add(tuple(m * x for x in p))
else:
break
m += 1
prim[i][1] = m # update multiplier for next loops
while buffer: # flush buffer
yield buffer.pop(0)
prim.append([pt, 2]) # add primitive to the list
def divisors(n):
'''
:param n: int
:return: all divisors of n: divisors(12) -> 1,2,3,6,12
including 1 and n,
except for 1 which returns a single 1 to avoid messing with sum of divisors...
'''
if n == 1:
yield 1
else:
all_factors = [[f ** p for p in itertools2.irange(0, fp)] for (f, fp) in factorize(n)]
# do not use itertools2.product here as long as the order of the result differs
for ns in itertools.product(*all_factors):
yield mul(ns)
def proper_divisors(n):
''':return: all divisors of n except n itself.'''
return (divisor for divisor in divisors(n) if divisor != n)
from bitarray import bitarray
class Sieve:
# should be derived from bitarray but ...
# https://github.com/ilanschnell/bitarray/issues/69
# TODO: simplify when solved
def __init__(self, f, init):
self._ = bitarray(init)
self.f = f
def __len__(self):
return len(self._)
def __getitem__(self, index):
return self._[index]
def __call__(self, n):
self.resize(n)
return (i for i, v in enumerate(self._) if v)
def resize(self, n):
l = len(self) - 1
if n <= l: return
n = int(n) # to tolerate n=1E9, which is float
self._.extend([True] * (n - l))
for i in self(n):
if i == 2:
i2, s = 4, 2
else:
i2, s = self.f(i)
if i2 > n: break
self._[i2::s] = False # bitarray([False]*int((n-i2)/s+1))
def erathostene(n):
return n * n, 2 * n
_sieve = Sieve(erathostene, [False, False, True]) # array of bool indicating primality
def sieve(n, oneisprime=False):
'''prime numbers from 2 to a prime < n
'''
res = _sieve(n)
if oneisprime:
res = itertools.chain([1], res)
return list(res)
_primes = sieve(1000) # primes up to 1000
_primes_set = set(_primes) # to speed us primality tests below
def primes(n):
'''memoized list of n first primes
:warning: do not call with large n, use prime_gen instead
'''
m = n - len(_primes)
if m > 0:
more = list(itertools2.take(m, primes_gen(_primes[-1] + 1)))
_primes.extend(more)