/
diophantine.py
2996 lines (2285 loc) · 82.8 KB
/
diophantine.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
import math
from ..core import (Add, Eq, Integer, Rational, Symbol, factor_terms,
integer_nthroot, oo, symbols, sympify)
from ..core.assumptions import check_assumptions
from ..core.compatibility import as_int
from ..core.function import _mexpand
from ..core.numbers import igcdex
from ..functions import floor, sign, sqrt
from ..matrices import Matrix
from ..ntheory import (divisors, factorint, is_square, isprime, multiplicity,
nextprime, perfect_power, sqrt_mod, square_factor)
from ..polys import GeneratorsNeededError, factor_list
from ..simplify import signsimp
from ..utilities import default_sort_key, filldedent, numbered_symbols
from ..utilities.iterables import is_sequence
from .solvers import solve
__all__ = 'diophantine', 'classify_diop'
# these types are known (but not necessarily handled)
diop_known = {
'binary_quadratic',
'cubic_thue',
'general_pythagorean',
'general_sum_of_even_powers',
'general_sum_of_squares',
'homogeneous_general_quadratic',
'homogeneous_ternary_quadratic',
'homogeneous_ternary_quadratic_normal',
'inhomogeneous_general_quadratic',
'inhomogeneous_ternary_quadratic',
'linear',
'univariate'}
def _is_int(i):
try:
as_int(i)
return True
except ValueError:
pass
def _sorted_tuple(*i):
return tuple(sorted(i))
def _remove_gcd(*x):
try:
g = math.gcd(*x)
return tuple(i//g for i in x)
except (TypeError, ValueError):
return x
def _rational_pq(a, b):
# return `(numer, denom)` for a/b; sign in numer and gcd removed
return _remove_gcd(sign(b)*a, abs(b))
def _nint_or_floor(p, q):
# return nearest int to p/q; in case of tie return floor(p/q)
w, r = divmod(p, q)
if abs(r) <= abs(q)//2:
return w
return w + 1
def _odd(i):
return i % 2 != 0
def _even(i):
return i % 2 == 0
def diophantine(eq, param=symbols('t', integer=True), syms=None):
"""
Simplify the solution procedure of diophantine equation ``eq`` by
converting it into a product of terms which should equal zero.
`(x + y)(x - y) = 0` and `x + y = 0` and `x - y = 0` are solved
independently and combined. Each term is solved by calling
``diop_solve()``.
Output of ``diophantine()`` is a set of tuples. The elements of the
tuple are the solutions for each variable in the the equation and
are arranged according to the alphabetic ordering of the variables.
e.g. For an equation with two variables, `a` and `b`, the first
element of the tuple is the solution for `a` and the second for `b`.
Parameters
==========
eq : Relational or Expr
an equation (to be solved)
t : Symbol, optional
the parameter to be used in the solution.
syms : list of Symbol's, optional
which determines the order of the elements in the returned tuple.
Examples
========
>>> diophantine(x**2 - y**2)
{(t_0, -t_0), (t_0, t_0)}
>>> diophantine(x*(2*x + 3*y - z))
{(0, n1, n2), (t_0, t_1, 2*t_0 + 3*t_1)}
>>> diophantine(x**2 + 3*x*y + 4*x)
{(0, n1), (3*t_0 - 4, -t_0)}
See Also
========
diofant.solvers.diophantine.diop_solve
"""
if isinstance(eq, Eq):
eq = eq.lhs - eq.rhs
if eq == 0:
return {(param,)}
try:
var = list(eq.expand(force=True).free_symbols)
var.sort(key=default_sort_key)
if syms:
if not is_sequence(syms):
raise TypeError('syms should be given as a sequence, e.g. a list')
syms = [i for i in syms if i in var]
if syms != var:
map = dict(zip(syms, range(len(syms))))
return {tuple(t[map[i]] for i in var)
for t in diophantine(eq, param)}
n, d = eq.as_numer_denom()
if not n.free_symbols:
return set()
if d.free_symbols:
dsol = diophantine(d)
good = diophantine(n) - dsol
return {s for s in good if _mexpand(d.subs(dict(zip(var, s))))}
eq = n
eq = factor_terms(eq)
assert not eq.is_number
eq = eq.as_independent(*var, as_Add=False)[1]
p = eq.as_poly()
assert not any(g.is_number for g in p.gens)
eq = p.as_expr()
assert eq.is_polynomial()
except (GeneratorsNeededError, AssertionError, AttributeError) as exc:
raise TypeError('Equation should be a polynomial with '
'Rational coefficients.') from exc
try:
# if we know that factoring should not be attempted, skip
# the factoring step
*_, t = classify_diop(eq)
if t == 'general_sum_of_squares':
# trying to factor such expressions will sometimes hang
terms = [(eq, 1)]
else:
raise TypeError
except (TypeError, NotImplementedError):
terms = factor_list(eq)[1]
sols = set()
for term in terms:
base, _ = term
var_t, _, eq_type = classify_diop(base, _dict=False)
_, base = signsimp(base, evaluate=False).as_coeff_Mul()
solution = diop_solve(base, param)
if eq_type in ['linear', 'homogeneous_ternary_quadratic',
'homogeneous_ternary_quadratic_normal',
'general_pythagorean']:
sols.add(merge_solution(var, var_t, solution))
elif eq_type in ['binary_quadratic', 'general_sum_of_squares',
'general_sum_of_even_powers', 'univariate']:
for sol in solution:
sols.add(merge_solution(var, var_t, sol))
else:
raise NotImplementedError(f'unhandled type: {eq_type}')
# remove null merge results
if () in sols:
sols.remove(())
null = tuple([0]*len(var))
# if there is no solution, return trivial solution
if not sols and eq.subs(dict.fromkeys(var, 0)) == 0:
sols.add(null)
return {sympify(i) for i in sols}
def merge_solution(var, var_t, solution):
"""
This is used to construct the full solution from the solutions of sub
equations.
For example when solving the equation `(x - y)(x^2 + y^2 - z^2) = 0`,
solutions for each of the equations `x - y = 0` and `x^2 + y^2 - z^2` are
found independently. Solutions for `x - y = 0` are `(x, y) = (t, t)`. But
we should introduce a value for z when we output the solution for the
original equation. This function converts `(t, t)` into `(t, t, n_{1})`
where `n_{1}` is an integer parameter.
"""
sol = []
if None in solution:
return ()
solution = iter(solution)
params = numbered_symbols('n', integer=True, start=1)
for v in var:
if v in var_t:
sol.append(next(solution))
else:
sol.append(next(params))
for val, symb in zip(sol, var):
if check_assumptions(val, **symb._assumptions) is False:
return ()
return tuple(sol)
def diop_solve(eq, param=symbols('t', integer=True)):
"""
Solves the diophantine equation ``eq``.
Unlike ``diophantine()``, factoring of ``eq`` is not attempted. Uses
``classify_diop()`` to determine the type of the equation and calls
the appropriate solver function.
Parameters
==========
eq : Expr
an expression, which is assumed to be zero.
t : Symbol, optional
a parameter, to be used in the solution.
Examples
========
>>> from diofant.abc import w
>>> diop_solve(2*x + 3*y - 5)
(3*t_0 - 5, -2*t_0 + 5)
>>> diop_solve(4*x + 3*y - 4*z + 5)
(t_0, 8*t_0 + 4*t_1 + 5, 7*t_0 + 3*t_1 + 5)
>>> diop_solve(x + 3*y - 4*z + w - 6)
(t_0, t_0 + t_1, 6*t_0 + 5*t_1 + 4*t_2 - 6, 5*t_0 + 4*t_1 + 3*t_2 - 6)
>>> diop_solve(x**2 + y**2 - 5)
{(-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)}
See Also
========
diofant.solvers.diophantine.diophantine
"""
var, coeff, eq_type = classify_diop(eq, _dict=False)
if eq_type == 'linear':
return _diop_linear(var, coeff, param)
if eq_type == 'binary_quadratic':
return _diop_quadratic(var, coeff, param)
if eq_type == 'homogeneous_ternary_quadratic':
x_0, y_0, z_0 = _diop_ternary_quadratic(var, coeff)
return _parametrize_ternary_quadratic((x_0, y_0, z_0), var, coeff)
if eq_type == 'homogeneous_ternary_quadratic_normal':
x_0, y_0, z_0 = _diop_ternary_quadratic_normal(var, coeff)
return _parametrize_ternary_quadratic((x_0, y_0, z_0), var, coeff)
if eq_type == 'general_pythagorean':
return _diop_general_pythagorean(var, coeff, param)
if eq_type == 'univariate':
l = solve(eq)
s = set()
for soln in l:
soln = list(soln.values())[0]
if isinstance(soln, Integer):
s.add((soln,))
return s
if eq_type == 'general_sum_of_squares':
return _diop_general_sum_of_squares(var, -int(coeff[1]), limit=oo)
if eq_type == 'general_sum_of_even_powers':
for k in coeff:
if k.is_Pow and coeff[k]:
p = k.exp
return _diop_general_sum_of_even_powers(var, p, -int(coeff[1]), limit=oo)
raise NotImplementedError(f'No solver has been written for {eq_type}.')
def classify_diop(eq, _dict=True):
try:
var = list(eq.free_symbols)
assert var
except (AttributeError, AssertionError) as exc:
raise ValueError('equation should have 1 or more free symbols') from exc
var.sort(key=default_sort_key)
eq = eq.expand(force=True)
coeff = eq.as_coefficients_dict()
if not all(_is_int(c) for c in coeff.values()):
raise TypeError('Coefficients should be Integers')
diop_type = None
total_degree = eq.as_poly().total_degree()
homogeneous = 1 not in coeff
if total_degree == 1:
diop_type = 'linear'
elif len(var) == 1:
diop_type = 'univariate'
elif total_degree == 2 and len(var) == 2:
diop_type = 'binary_quadratic'
elif total_degree == 2 and len(var) == 3 and homogeneous:
if set(coeff) & set(var):
diop_type = 'inhomogeneous_ternary_quadratic'
else:
nonzero = [k for k in coeff if coeff[k]]
if len(nonzero) == 3 and all(i**2 in nonzero for i in var):
diop_type = 'homogeneous_ternary_quadratic_normal'
else:
diop_type = 'homogeneous_ternary_quadratic'
elif total_degree == 2 and len(var) >= 3:
if set(coeff) & set(var):
diop_type = 'inhomogeneous_general_quadratic'
else:
# there may be Pow keys like x**2 or Mul keys like x*y
if any(k.is_Mul for k in coeff): # cross terms
if not homogeneous:
diop_type = 'inhomogeneous_general_quadratic'
else:
diop_type = 'homogeneous_general_quadratic'
else: # all squares: x**2 + y**2 + ... + constant
if all(coeff[k] == 1 for k in coeff if k != 1):
diop_type = 'general_sum_of_squares'
elif all(is_square(abs(coeff[k])) for k in coeff):
if abs(sum(sign(coeff[k]) for k in coeff)) == len(var) - 2:
# all but one has the same sign
# e.g. 4*x**2 + y**2 - 4*z**2
diop_type = 'general_pythagorean'
elif total_degree == 3 and len(var) == 2:
diop_type = 'cubic_thue'
elif (total_degree > 3 and total_degree % 2 == 0 and
all(k.is_Pow and k.exp == total_degree for k in coeff if k != 1)):
if all(coeff[k] == 1 for k in coeff if k != 1):
diop_type = 'general_sum_of_even_powers'
if diop_type is not None:
return var, dict(coeff) if _dict else coeff, diop_type
# new diop type instructions
# --------------------------
# if this error raises and the equation *can* be classified,
# * it should be identified in the if-block above
# * the type should be added to the diop_known
# if a solver can be written for it,
# * a dedicated handler should be written (e.g. diop_linear)
# * it should be passed to that handler in diop_solve
raise NotImplementedError(filldedent("""
This equation is not yet recognized or else has not been
simplified sufficiently to put it in a form recognized by
diop_classify()."""))
classify_diop.__doc__ = """
Helper routine used by diop_solve() to find the type of the ``eq`` etc.
Parameters
==========
eq : Expr
an expression, which is assumed to be zero.
Examples
========
>>> classify_diop(4*x + 6*y - 4)
([x, y], {1: -4, x: 4, y: 6}, 'linear')
>>> classify_diop(x + 3*y - 4*z + 5)
([x, y, z], {1: 5, x: 1, y: 3, z: -4}, 'linear')
>>> classify_diop(x**2 + y**2 - x*y + x + 5)
([x, y], {1: 5, x: 1, x**2: 1, y**2: 1, x*y: -1}, 'binary_quadratic')
Returns
=======
Returns a tuple containing the type of the diophantine equation along with
the variables(free symbols) and their coefficients. Variables are returned
as a list and coefficients are returned as a dict with the key being the
respective term and the constant term is keyed to Integer(1). The type
is one of the following:
* %s
""" % ('\n * '.join(sorted(diop_known))) # noqa: SFS101
def diop_linear(eq, param=symbols('t', integer=True)):
"""
Solves linear diophantine equations.
A linear diophantine equation is an equation of the form `a_{1}x_{1} +
a_{2}x_{2} + .. + a_{n}x_{n} = 0` where `a_{1}, a_{2}, ..a_{n}` are
integer constants and `x_{1}, x_{2}, ..x_{n}` are integer variables.
Parameters
==========
eq : Expr
is a linear diophantine equation which is assumed to be zero.
param : Symbol, optional
is the parameter to be used in the solution.
Examples
========
>>> diop_linear(2*x - 3*y - 5)
(3*t_0 - 5, 2*t_0 - 5)
Here x = -3*t_0 - 5 and y = -2*t_0 - 5
>>> diop_linear(2*x - 3*y - 4*z - 3)
(t_0, 2*t_0 + 4*t_1 + 3, -t_0 - 3*t_1 - 3)
See Also
========
diofant.solvers.diophantine.diop_quadratic
diofant.solvers.diophantine.diop_ternary_quadratic
diofant.solvers.diophantine.diop_general_pythagorean
diofant.solvers.diophantine.diop_general_sum_of_squares
"""
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type == 'linear':
return _diop_linear(var, coeff, param)
def _diop_linear(var, coeff, param):
"""
Solves diophantine equations of the form:
a_0*x_0 + a_1*x_1 + ... + a_n*x_n == c
Note that no solution exists if gcd(a_0, ..., a_n) doesn't divide c.
"""
if 1 in coeff:
# negate coeff[] because input is of the form: ax + by + c == 0
# but is used as: ax + by == -c
c = -coeff[1]
else:
c = Integer(0)
# Some solutions will have multiple free variables in their solutions.
if param is None:
params = [symbols('t')]*len(var)
else:
temp = str(param) + '_%i'
params = [symbols(temp % i, integer=True) for i in range(len(var))]
if len(var) == 1:
q, r = divmod(c, coeff[var[0]])
if not r:
return q,
return None,
# base_solution_linear() can solve diophantine equations of the form:
#
# a*x + b*y == c
#
# We break down multivariate linear diophantine equations into a
# series of bivariate linear diophantine equations which can then
# be solved individually by base_solution_linear().
#
# Consider the following:
#
# a_0*x_0 + a_1*x_1 + a_2*x_2 == c
#
# which can be re-written as:
#
# a_0*x_0 + g_0*y_0 == c
#
# where
#
# g_0 == gcd(a_1, a_2)
#
# and
#
# y == (a_1*x_1)/g_0 + (a_2*x_2)/g_0
#
# This leaves us with two binary linear diophantine equations.
# For the first equation:
#
# a == a_0
# b == g_0
# c == c
#
# For the second:
#
# a == a_1/g_0
# b == a_2/g_0
# c == the solution we find for y_0 in the first equation.
#
# The arrays A and B are the arrays of integers used for
# 'a' and 'b' in each of the n-1 bivariate equations we solve.
A = [coeff[v] for v in var]
B = []
if len(var) > 2:
B.append(math.gcd(A[-2], A[-1]))
A[-2] = A[-2] // B[0]
A[-1] = A[-1] // B[0]
for i in range(len(A) - 3, 0, -1):
gcd = math.gcd(B[0], A[i])
B[0] = B[0] // gcd
A[i] = A[i] // gcd
B.insert(0, gcd)
B.append(A[-1])
# Consider the trivariate linear equation:
#
# 4*x_0 + 6*x_1 + 3*x_2 == 2
#
# This can be re-written as:
#
# 4*x_0 + 3*y_0 == 2
#
# where
#
# y_0 == 2*x_1 + x_2
# (Note that gcd(3, 6) == 3)
#
# The complete integral solution to this equation is:
#
# x_0 == 2 + 3*t_0
# y_0 == -2 - 4*t_0
#
# where 't_0' is any integer.
#
# Now that we have a solution for 'x_0', find 'x_1' and 'x_2':
#
# 2*x_1 + x_2 == -2 - 4*t_0
#
# We can then solve for '-2' and '-4' independently,
# and combine the results:
#
# 2*x_1a + x_2a == -2
# x_1a == 0 + t_0
# x_2a == -2 - 2*t_0
#
# 2*x_1b + x_2b == -4*t_0
# x_1b == 0*t_0 + t_1
# x_2b == -4*t_0 - 2*t_1
#
# ==>
#
# x_1 == t_0 + t_1
# x_2 == -2 - 6*t_0 - 2*t_1
#
# where 't_0' and 't_1' are any integers.
#
# Note that:
#
# 4*(2 + 3*t_0) + 6*(t_0 + t_1) + 3*(-2 - 6*t_0 - 2*t_1) == 2
#
# for any integral values of 't_0', 't_1'; as required.
#
# This method is generalized for many variables, below.
solutions = []
for i, Bi in enumerate(B):
tot_x, tot_y = [], []
for arg in Add.make_args(c):
if arg.is_Integer:
# example: 5 -> k = 5
k, p = arg, Integer(1)
pnew = params[0]
else: # arg is a Mul or Symbol
# example: 3*t_1 -> k = 3
# example: t_0 -> k = 1
k, p = arg.as_coeff_Mul()
pnew = params[params.index(p) + 1]
sol = sol_x, sol_y = base_solution_linear(k, A[i], Bi, pnew)
if p == 1:
if None in sol:
return tuple([None]*len(var))
else:
# convert a + b*pnew -> a*p + b*pnew
if isinstance(sol_x, Add):
sol_x = sol_x.args[0]*p + sol_x.args[1]
if isinstance(sol_y, Add):
sol_y = sol_y.args[0]*p + sol_y.args[1]
tot_x.append(sol_x)
tot_y.append(sol_y)
solutions.append(Add(*tot_x))
c = Add(*tot_y)
solutions.append(c)
if param is None:
# just keep the additive constant (i.e. replace t with 0)
solutions = [i.as_coeff_Add()[0] for i in solutions]
return tuple(solutions)
def base_solution_linear(c, a, b, t=None):
"""
Return the base solution for the linear equation, `ax + by = c`.
Used by ``diop_linear()`` to find the base solution of a linear
Diophantine equation. If ``t`` is given then the parametrized solution is
returned.
``base_solution_linear(c, a, b, t)``: ``a``, ``b``, ``c`` are coefficients
in `ax + by = c` and ``t`` is the parameter to be used in the solution.
Examples
========
>>> base_solution_linear(5, 2, 3) # equation 2*x + 3*y = 5
(-5, 5)
>>> base_solution_linear(0, 5, 7) # equation 5*x + 7*y = 0
(0, 0)
>>> base_solution_linear(5, 2, 3, t) # equation 2*x + 3*y = 5
(3*t - 5, -2*t + 5)
>>> base_solution_linear(0, 5, 7, t) # equation 5*x + 7*y = 0
(7*t, -5*t)
"""
a, b, c = _remove_gcd(a, b, c)
if c == 0:
if t is not None:
if b < 0:
t = -t
return b*t, -a*t
return 0, 0
x0, y0, d = igcdex(abs(a), abs(b))
x0 *= sign(a)
y0 *= sign(b)
if divisible(c, d):
if t is not None:
if b < 0:
t = -t
return c*x0 + b*t, c*y0 - a*t
return c*x0, c*y0
return None, None
def divisible(a, b):
"""Returns `True` if ``a`` is divisible by ``b`` and `False` otherwise."""
return not a % b
def diop_quadratic(eq, param=symbols('t', integer=True)):
"""
Solves quadratic diophantine equations.
i.e. equations of the form `Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0`. Returns a
set containing the tuples `(x, y)` which contains the solutions. If there
are no solutions then `(None, None)` is returned.
Parameters
==========
eq : Expr
should be a quadratic bivariate expression which is assumed
to be zero.
param : Symbol, optional
is a parameter to be used in the solution.
Examples
========
>>> diop_quadratic(x**2 + y**2 + 2*x + 2*y + 2, t)
{(-1, -1)}
References
==========
* Methods to solve Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0, [online],
Available: https://web.archive.org/web/20181231080858/https://www.alpertron.com.ar/METHODS.HTM
* Solving the equation ax^2+ bxy + cy^2 + dx + ey + f= 0, [online],
Available: https://web.archive.org/web/20180831180321/http://www.jpr2718.org/ax2p.pdf
See Also
========
diofant.solvers.diophantine.diop_linear
diofant.solvers.diophantine.diop_ternary_quadratic
diofant.solvers.diophantine.diop_general_sum_of_squares
diofant.solvers.diophantine.diop_general_pythagorean
"""
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type == 'binary_quadratic':
return _diop_quadratic(var, coeff, param)
def _diop_quadratic(var, coeff, t):
x, y = var
A = coeff[x**2]
B = coeff[x*y]
C = coeff[y**2]
D = coeff[x]
E = coeff[y]
F = coeff[1]
A, B, C, D, E, F = map(as_int, _remove_gcd(A, B, C, D, E, F))
# (1) Simple-Hyperbolic case: A = C = 0, B != 0
# In this case equation can be converted to (Bx + E)(By + D) = DE - BF
# We consider two cases; DE - BF = 0 and DE - BF != 0
# More details, https://web.archive.org/web/20181231080858/https://www.alpertron.com.ar/METHODS.HTM#SHyperb
sol = set()
discr = B**2 - 4*A*C
if A == 0 and C == 0 and B != 0:
if D*E - B*F == 0:
q, r = divmod(E, B)
if not r:
sol.add((-q, t))
q, r = divmod(D, B)
if not r:
sol.add((t, -q))
else:
div = divisors(D*E - B*F)
div = div + [-term for term in div]
for d in div:
x0, r = divmod(d - E, B)
if not r:
q, r = divmod(D*E - B*F, d)
assert not r
y0, r = divmod(q - D, B)
if not r:
sol.add((x0, y0))
# (2) Parabolic case: B**2 - 4*A*C = 0
# There are two subcases to be considered in this case.
# sqrt(c)D - sqrt(a)E = 0 and sqrt(c)D - sqrt(a)E != 0
# More Details, https://web.archive.org/web/20181231080858/https://www.alpertron.com.ar/METHODS.HTM#Parabol
elif discr == 0:
if A == 0:
s = _diop_quadratic([y, x], coeff, t)
for soln in s:
sol.add((soln[1], soln[0]))
else:
g = sign(A)*math.gcd(A, C)
a = A // g
c = C // g
e = sign(B/A)
sqa = math.isqrt(a)
sqc = math.isqrt(c)
_c = e*sqc*D - sqa*E
if not _c:
z = symbols('z', extended_real=True)
roots = solve(sqa*g*z**2 + D*z + sqa*F, z)
for root in roots:
root = root[z]
if isinstance(root, Integer):
ans = diop_solve(sqa*x + e*sqc*y - root)
sol.add((ans[0], ans[1]))
else:
def solve_x(u):
return -e*sqc*g*_c*t**2 - (E + 2*e*sqc*g*u)*t - (e*sqc*g*u**2 + E*u + e*sqc*F) // _c
def solve_y(u):
return sqa*g*_c*t**2 + (D + 2*sqa*g*u)*t + (sqa*g*u**2 + D*u + sqa*F) // _c
for z0 in range(0, abs(_c)):
if (divisible(sqa*g*z0**2 + D*z0 + sqa*F, _c) and
divisible(e*sqc**g*z0**2 + E*z0 + e*sqc*F, _c)):
sol.add((solve_x(z0), solve_y(z0)))
# (3) Method used when B**2 - 4*A*C is a square, is described in p. 6 of the below paper
# by John P. Robertson, https://web.archive.org/web/20180831180321/http://www.jpr2718.org/ax2p.pdf
elif is_square(discr):
if A != 0:
r = sqrt(discr)
u, v = symbols('u, v', integer=True)
eq = _mexpand(4*A*r*u*v + 4*A*D*(B*v + r*u + r*v - B*u) +
2*A*4*A*E*(u - v) + 4*A*r*4*A*F)
solution = diop_solve(eq, t)
for s0, t0 in solution:
num = B*t0 + r*s0 + r*t0 - B*s0
x_0 = num/(4*A*r)
y_0 = (s0 - t0)/(2*r)
if ((isinstance(s0, Symbol) or isinstance(t0, Symbol)) and
check_param(x_0, y_0, 4*A*r, t) != (None, None)):
ans = check_param(x_0, y_0, 4*A*r, t)
sol.add((ans[0], ans[1]))
elif x_0.is_Integer and y_0.is_Integer and is_solution_quad(var, coeff, x_0, y_0):
sol.add((x_0, y_0))
else:
s = _diop_quadratic(var[::-1], coeff, t) # Interchange x and y
while s:
sol.add(s.pop()[::-1]) # and solution <--
# (4) B**2 - 4*A*C > 0 and B**2 - 4*A*C not a square or B**2 - 4*A*C < 0
else:
P, Q = _transformation_to_DN(var, coeff)
D, N = _find_DN(var, coeff)
solns_pell = diop_DN(D, N)
if D < 0:
for x0, y0 in solns_pell:
for x in [-x0, x0]:
for y in [-y0, y0]:
s = P*Matrix([x, y]) + Q
try:
sol.add(tuple(as_int(_) for _ in s))
except ValueError:
pass
else:
# In this case equation can be transformed into a Pell equation
solns_pell = set(solns_pell)
for X, Y in list(solns_pell):
solns_pell.add((-X, -Y))
a = diop_DN(D, 1)
T = a[0][0]
U = a[0][1]
if all(_is_int(_) for _ in P[:4] + Q[:2]):
for r, s in solns_pell:
_a = (r + s*sqrt(D))*(T + U*sqrt(D))**t
_b = (r - s*sqrt(D))*(T - U*sqrt(D))**t
x_n = _mexpand((_a + _b)/2)
y_n = _mexpand((_a - _b)/(2*sqrt(D)))
s = P*Matrix([x_n, y_n]) + Q
sol.add(tuple(s))
else:
L = math.lcm(*(_.denominator for _ in P[:4] + Q[:2]))
k = 1
T_k = T
U_k = U
while (T_k - 1) % L != 0 or U_k % L != 0:
T_k, U_k = T_k*T + D*U_k*U, T_k*U + U_k*T
k += 1
for X, Y in solns_pell:
for _ in range(k):
if all(_is_int(_) for _ in P*Matrix([X, Y]) + Q):
_a = (X + sqrt(D)*Y)*(T_k + sqrt(D)*U_k)**t
_b = (X - sqrt(D)*Y)*(T_k - sqrt(D)*U_k)**t
Xt = (_a + _b)/2
Yt = (_a - _b)/(2*sqrt(D))
s = P*Matrix([Xt, Yt]) + Q
sol.add(tuple(s))
X, Y = X*T + D*U*Y, X*U + Y*T
return sol
def is_solution_quad(var, coeff, u, v):
"""
Check whether `(u, v)` is solution to the quadratic binary diophantine
equation with the variable list ``var`` and coefficient dictionary
``coeff``.
Not intended for use by normal users.
"""
reps = dict(zip(var, (u, v)))
eq = Add(*[j*i.xreplace(reps) for i, j in coeff.items()])
return _mexpand(eq) == 0
def diop_DN(D, N, t=symbols('t', integer=True)):
"""
Solves the equation `x^2 - Dy^2 = N`.
Mainly concerned with the case `D > 0, D` is not a perfect square,
which is the same as the generalized Pell equation. The LMM
algorithm is used to solve this equation.
Returns
=======
A tuple of pairs, (`x, y)`, for each class of the solutions.
Other solutions of the class can be constructed according to the
values of ``D`` and ``N``.
Parameters
==========
D, N : Integer
correspond to D and N in the equation.
t : Symbol, optional
is the parameter to be used in the solutions.
Examples
========
>>> diop_DN(13, -4) # Solves equation x**2 - 13*y**2 = -4
[(3, 1), (393, 109), (36, 10)]
The output can be interpreted as follows: There are three fundamental
solutions to the equation `x^2 - 13y^2 = -4` given by (3, 1), (393, 109)
and (36, 10). Each tuple is in the form (x, y), i.e. solution (3, 1) means
that `x = 3` and `y = 1`.
>>> diop_DN(986, 1) # Solves equation x**2 - 986*y**2 = 1
[(49299, 1570)]
See Also
========
diofant.solvers.diophantine.find_DN
diofant.solvers.diophantine.diop_bf_DN
References
==========
* Solving the generalized Pell equation x**2 - D*y**2 = N, John P.
Robertson, July 31, 2004, Pages 16 - 17. [online], Available:
https://web.archive.org/web/20180831180333/http://www.jpr2718.org/pell.pdf
"""
if D < 0:
if N == 0:
return [(0, 0)]
if N < 0:
return []
# N > 0
sol = []
for d in divisors(square_factor(N)):
sols = cornacchia(1, -D, N // d**2)
if sols:
for x, y in sols:
sol.append((d*x, d*y))
if D == -1:
sol.append((d*y, d*x))
return sol
if D == 0:
if N < 0:
return []
if N == 0:
return [(0, t)]
sN, _exact = integer_nthroot(N, 2)
if _exact:
return [(sN, t)]
return []
# D > 0
sD, _exact = integer_nthroot(D, 2)