-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDiophantineSolverMk2.cpp
2687 lines (2451 loc) · 78 KB
/
DiophantineSolverMk2.cpp
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
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#include "stdafx.h"
#include <windows.h>
// Diophantine Quadratic Equation Solver
// ax^2 + bxy + cy^2 + dx + ey + f = 0 (unknowns x,y integer numbers)
//
// Written by Dario Alejandro Alpern (Buenos Aires - Argentina)
// (Last updated December 15th, 2003)
//
// No part of this code can be used for commercial purposes without
// the written consent from the author. Otherwise it can be used freely.
//
// converted fron Java to C++ by R Atherton, Octobler 2017
// because of problems with java not being supported by web browsers.
//using namespace std;
/* following used to detect memory leakage */
_CrtMemState memState1; // initial memory state
_CrtMemState memState2; // current memory state
_CrtMemState memStatDiff; // difference between initial and current memory state
std::string info;
std::string txt;
//const std::string sq = "²"; // would be nice to use, but causes problems
const std::string sq = "^2";
const std::string msg = "There are no solutions !!!\n";
std::string number;
bool also = false, ExchXY = false, teach = false;
bool allSolsFound;
const std::string divgcd = "Dividing the equation by the GCD we obtain: \n";
long long g_A, g_B, g_C, g_D, g_E, g_F;
long long g_Xi, g_Xl, g_Yi, g_Yl;
long long g_CY1, g_CY0;
long long g_A2, g_B2;
long long g_Disc;
mpz_t Dp_NUM, Dp_DEN;
unsigned long long SqrtDisc;
/* large numbers; shown by Bi_ prefix */
mpz_t Bi_H1, Bi_H2, Bi_K1, Bi_K2, Bi_L1, Bi_L2;
int NbrSols = 0, NbrCo;
int digitsInGroup = 6; // used in ShowLargeNumber
/* typedef for vector-type arrays */
typedef std::vector <void *> ArrayLongs;
ArrayLongs sortedSolsXv ;
ArrayLongs sortedSolsYv ;
void listLargeSolutions();
/* print a string variable. This is a relic from the original java program */
void w(std::string texto) {
// info = info.append(texto);
std::cout << texto;
}
/* calculate integer square root */
unsigned long long llSqrt(unsigned long long num) {
unsigned long long num1 = 0;
unsigned long long num2 = (long long)65536 * (long long)32768; /* 2^31 */
while (num2 != 0) {
if ((num1 + num2)*(num1 + num2) <= num) {
num1 += num2;
}
num2 /= 2;
}
return num1;
}
/* Out = Nbr */
void LongToDoublePrecLong(long long Nbr, mpz_t Dp_Out) {
mpz_set_si(Dp_Out, Nbr);
}
/* calculate Greatest Common Divisor */
long long gcd(long long M, long long N) {
long long P = M;
long long Q = N;
while (P != 0) {
long long R = Q%P;
Q = P;
P = R;
}
return abs(Q);
}
/* calculate Greatest Common Divisor for Bigints*/
void gcd(const mpz_t Dp_Nbr1, const mpz_t Dp_Nbr2, mpz_t Dp_Gcd) {
mpz_gcd(Dp_Gcd, Dp_Nbr1, Dp_Nbr2);
}
/* convert double to a string */
//std::string doubToStr(double num) {
// char numbr[21];
// sprintf_s(numbr, sizeof(numbr), "%g", num);
// number = numbr; // copy to C++ string
// return number;
//}
void showAlso() {
if (also) {
printf("and also: ");
}
else {
also = true;
}
}
/* print values of X and Y */
void ShowXY(long long X, long long Y) {
showAlso();
if (!ExchXY) {
//w("x = " + numToStr(X));
printf("x = %lld y = %lld \n", X, Y);
//w("\ny = " + numToStr(Y) + "\n");
}
else {
//w("x = " + numToStr(Y));
printf("x = %lld y = %lld \n", Y, X);
//w("\ny = " + numToStr(X) + "\n");
}
}
/* calculate and print values of X and Y. */
void ShowX1Y1(long long X1, long long Y1, long long A, long long B, long long D,
long long D1, long long E1) {
long long X, Y;
if ((Y1 - E1) % D1 == 0) {
Y = (Y1 - E1) / D1;
if ((X1 - B*Y - D) % (2 * A) == 0) {
X = (X1 - B*Y - D) / (2 * A);
ShowXY(X, Y); // display solution
}
if (X1 != 0 && (-X1 - B*Y - D) % (2 * A) == 0) {
X = (-X1 - B*Y - D) / (2 * A);
ShowXY(X, Y); // display solution
}
}
if (Y1 != 0 && (-Y1 - E1) % D1 == 0) {
Y = (-Y1 - E1) / D1;
if ((X1 - B*Y - D) % (2 * A) == 0) {
X = (X1 - B*Y - D) / (2 * A);
ShowXY(X, Y); // display solution
}
if (X1 != 0 && (-X1 - B*Y - D) % (2 * A) == 0) {
X = (-X1 - B*Y - D) / (2 * A);
ShowXY(X, Y); // display solution
}
}
}
/* output value of num. Uses global variable txt.
iff t is odd, use '+' for +ve numbers.
if t =2 result is left in txt and not output.
if num is zero do nothing */
int Show(long long num, std::string str, int t) {
if (t == 2) {
txt = ""; // clear contents of txt
}
if (num != 0) {
std::string str1 = "";
if ((t & 1) != 0 && num>0) {
str1 += " +";
}
if (num<0) {
str1 += " -";
}
if (abs(num) != 1) {
str1 += " " + numToStr(abs(num));
}
str1 += str;
if ((t & 2) != 0) {
txt += str1;
}
else {
//printf("%s", str1.c_str());
std::cout << str1;
}
return (t | 1); // return type bit for next time
}
return t;
}
void Show1(long long num, int t) {
char u = Show(num, "", t);
if ((u & 1) == 0 || abs(num) == 1) {
if ((u & 2) != 0) {
txt += numToStr(abs(num));
}
else {
//w("" + numToStr(abs(num)));
std::cout << abs(num);
}
}
}
/* print values of D, E and F */
void ShowLin(long long D, long long E, long long F, std::string x, std::string y) {
int t = Show(D, x, 0);
t = Show(E, y, t);
Show1(F, t);
}
/* print "ax^2 + Bxy + Cy^2 +Dx + Ey + F" */
void ShowEq(long long A, long long B, long long C, long long D, long long E, long long F,
std::string x, std::string y) {
int t = Show(A, x + sq, 0);
t = Show(B, x + y, t);
t = Show(C, y + sq, t);
t = Show(D, x, t);
t = Show(E, y, t);
Show1(F, t);
}
/* print " so there are no integer solutions" and set also to 'true' */
void NoSol() {
printf(" so there are no integer solutions.\n");
also = true;
}
void NoGcd(long long F) {
if (teach) {
std::cout << "This gcd is not a divisor of the constant term (" << F << ")," << "\n";
}
NoSol();
}
/* Nbr = -Nbr*/
void ChangeSign(mpz_t Bi_Nbr) {
mpz_neg(Bi_Nbr, Bi_Nbr);
}
/* for some reason these functions don´t exist already int he GMP/MPIR library*/
void mpz_add_si(mpz_t rop, const mpz_t op1, mpir_si op2) {
mpir_ui ui;
if (op2 >= 0) {
mpz_add_ui(rop, op1, op2);
}
else {
// careful: overflow when negating INT_MIN
ui = abs(op2); // change sign of op2
mpz_sub_ui(rop, op1, ui);
}
}
void mpz_sub_si(mpz_t rop, const mpz_t op1, mpir_si op2) {
mpir_ui ui;
if (op2 >= 0) {
mpz_sub_ui(rop, op1, op2);
}
else {
// careful: overflow when negating INT_MIN
ui = abs(op2); // change sign of op2
mpz_add_ui(rop, op1, ui);
}
}
long long floordiv(long long num, long long den) {
if ((num<0 && den>0 || num>0 && den<0) && num%den != 0) {
return num / den - 1;
}
return num / den;
}
// commented out because it's not actually used
//long long ceildiv(long long num, long long den) {
// if ((num>0 && den>0 || num<0 && den<0) && num%den != 0) {
// return num / den + 1;
// }
// return num / den;
//}
/* q = n/d. return quotient as a bigint. Uses floor division.
i.e. rounds q down towards -infinity. The only difference from
< DivLargeNumber> is that this function does not return a value but
< DivLargeNumber> returns the remainder as a long long. */
void DivideDoublePrecLong(const mpz_t n, const mpz_t d, mpz_t q) {
mpz_fdiv_q(q, n, d); // note use of floor division
}
/* q = n/d return value is remainder. Uses floor division
i.e. rounds q down towards -infinity, and r will have the same sign as d.
the 3 different types of division only give different results when
the remainder is non-zero and n or d (or both) are negative.
NB. The choice of floor or truncation type division is sometimes
critical, and the correct choice is not obvious. */
long long DivLargeNumber(const mpz_t n, long long d, mpz_t q) {
long long remainder;
mpz_t mpr, mpd, nsave;
if (d == 0) {
fprintf(stderr, "** divide by zero error\n");
abort();
}
/* because no mpz_fdiv_q_si exists in the library we need to convert the divisor to a bigint */
mpz_init_set_si(mpd, d); // mpd = d
mpz_init_set(nsave, n); // nsave = n
mpz_init(mpr);
mpz_fdiv_qr(q, mpr, n, mpd); // q = n/d, mpr=remainder
remainder = mpz_get_si(mpr); // magnitude of remainder is < d, so it can't overflow
if (remainder != 0) {
//gmp_printf("**temp DivLargeNumber %Zd/%lld = %Zd rem=%lld \n", nsave, d, q, remainder);
}
mpz_clears(mpr, mpd, nsave, NULL);
return remainder;
}
/* q = n/d return value is remainder. Uses 'truncate' division
i.e. rounds q towards zero, and remainder will have the same sign as n.
the 3 different types of division only give different results when
the remainder is non-zero and n or d (or both) are negative
NB. The choice of floor or truncation type division is sometimes
critical, and the correct choice is not obvious. */
long long tDivLargeNumber(const mpz_t n, long long d, mpz_t q) {
long long remainder;
mpz_t mpr, mpd, nsave;
if (d == 0) {
fprintf(stderr, "** divide by zero error\n");
abort();
}
/* because no mpz_tdiv_q_si exists in the library we need to convert the divisor to a bigint */
mpz_init_set_si(mpd, d); // mpd = d
mpz_init_set(nsave, n); // nsave = n
mpz_init(mpr);
mpz_tdiv_qr(q, mpr, n, mpd); // q = n/d, mpr=remainder
remainder = mpz_get_si(mpr); // magnitude of remainder is < d, so it can't overflow
if (remainder != 0) {
//gmp_printf("**temp tDivLargeNumber %Zd/%lld = %Zd rem=%lld \n", nsave, d, q, remainder);
}
mpz_clears(mpr, mpd, nsave, NULL);
return remainder;
}
/* return quotient (= n/d) as a normal integer. uses floor division
i.e. rounds q down towards -infinity, and r will have the same sign as d.*/
long long DivDoublePrec(const mpz_t n, const mpz_t d) {
mpz_t q, r;
long long llquot;
mpz_inits(q, r, NULL);
mpz_fdiv_qr(q, r, n, d); // note use of floor division
assert(mpz_fits_slong_p(q) != 0); // is quotient too big for normal integer?
llquot = mpz_get_si(q); // convert to normal integer
/*if (!IsZero(r)) {
gmp_printf("**temp DivDoublePrec: %Zd = %Zd/%Zd rem=%Zd \n", q, n, d, r);
}*/
mpz_clears(q, r, NULL); // avoid memory leakage
return llquot;
}
/* Dest = Cprev*Bi_Prev + CAct*Bi_Act */
void MultAddLargeNumbers(long long CPrev, const mpz_t Bi_Prev,
long long CAct, const mpz_t Bi_Act, mpz_t Bi_Dest) {
mpz_t temp1, temp2;
mpz_inits(temp1, temp2, NULL);
mpz_mul_si(temp1, Bi_Prev, CPrev); // temp1 = Cprev*Bi_Prev
mpz_mul_si(temp2, Bi_Act, CAct); // temp2 = CAct*Bi_Act
mpz_add(Bi_Dest, temp1, temp2); // Dest = Cprev*Bi_Prev + CAct*Bi_Act
mpz_clears(temp1, temp2, NULL);
}
/* calculate K and L. values are returned in Bi_H1, Bi_K1, Bi_L1 and Bi_L2
It returns true if K and L are valid
Uses input global variables g_A, g_B, g_C, g_D, g_E, Bi_H2, Bi_K2
called from ShowSols */
bool CalculateKandL() {
/*std::cout << "**temp CalculateKandL "
<< " Bi_H2=" << numToString(Bi_H2) << " Bi_K2=" << numToString(Bi_K2);
std::cout << " A=" << g_A << " B=" << g_B << " C=" << g_C << " D=" << g_D
<< " E=" << g_E << "\n";*/
MultAddLargeNumbers(2, Bi_H2, g_B, Bi_K2, Bi_L1); /* 2r + Bs */
AddLarge(Bi_L1, -2, Bi_H1); /* Kd = 2r + Bs - 2 */
AddLarge(Bi_H2, -1, Bi_K1); /* r - 1 */
MultAddLargeNumbers(-g_B, Bi_K1, -2 * g_A*g_C, Bi_K2, Bi_K1); /* Ke */
MultAddLargeNumbers(g_C*g_D, Bi_H1, g_E, Bi_K1, Bi_L1); /* K(4AC - BB) */
if (tDivLargeNumber(Bi_L1, 4 * g_A*g_C - g_B*g_B, Bi_L1) != 0) { /* K */
//std::cout <<"**temp CalculateKandL: K not integer; return false\n";
return false; /* K not integer */
}
MultAddLargeNumbers(g_D, Bi_K1, g_A*g_E, Bi_H1, Bi_L2);
/*std::cout << "**temp CalculateKandL " << " Bi_L2=" << numToString(Bi_L2)
<< " Divisor = " << 4 * g_A*g_C - g_B*g_B << "\n";*/
if (tDivLargeNumber(Bi_L2, 4 * g_A*g_C - g_B*g_B, Bi_L2) != 0) {
/*std::cout << "**temp CalculateKandL: L not integer; return false\n";*/
return false; /* L not integer */
}
MultAddLargeNumbers(1, Bi_L2, g_D, Bi_K2, Bi_L2); /* L */
//std::cout << "**temp CalculateKandL: Bi_L2=" << numToString(Bi_L2) << "\n";
return true;
}
/* print large number. */
void ShowLargeNumber(const mpz_t Bi_Nbr){
std::string nbrOutput = "";
char* buffer = NULL;
size_t msglen, index=0;
// convert to null-terminated ascii string, base 10, with sign if -ve
buffer = mpz_get_str(NULL, 10, Bi_Nbr);
msglen = strnlen(buffer, 50000); // arbitrary limit of 50000
if (buffer[0] == '-') { // if number is -ve
nbrOutput = "-";
index = 1;
}
for (; index < msglen; index++) {
if ((msglen - index) % digitsInGroup == 0) {
// divide digits into groups, if there are more than 6 digits
if ((index > 0 && buffer[0] != '-')|| (index > 1))
nbrOutput += " ";
}
nbrOutput += buffer[index];
}
if (buffer[0] == '-') // if number is -ve
msglen--;
free(buffer); // avoid memory leakage
std::cout << nbrOutput;
if (msglen > 6)
std::cout << " (" << msglen << " digits)";
}
/* Dest = Nbr*Coef */
void MultLargeNumber(long long Coef, const mpz_t Bi_Nbr, mpz_t Bi_Dest) {
mpz_mul_si(Bi_Dest, Bi_Nbr, Coef);
}
/* Dest = Nbr1 *Nbr2 */
void Mult2LargeNumbers(const mpz_t Bi_Nbr1, const mpz_t Bi_Nbr2, mpz_t Bi_Dest) {
mpz_mul(Bi_Dest, Bi_Nbr1, Bi_Nbr2);
}
/* called from ShowRecursionRoot. Uses global variables:
Bi_H1, Bi_H2, Bi_K2, Bi_L1, Bi_L2, A, C
type = hyperbolic_homog (homogenous) or hyperbolic_gen (general hyperbolic)
return 1 if K or L not integers, otherwise zero
If K and L are integers, print values for P, Q, K, R, S, L*/
int ShowSols(equation_class type) {
//std::cout << "**temp ShowSols Bi_H2=" << numToString(Bi_H2)
// << " Bi_K2=" << numToString(Bi_K2) << " g_C=" << g_C << "\n";
if (type == hyperbolic_gen) {
if (!CalculateKandL()) { /* if K or L not integers */
return 1; /* bye */
}
/* values for K and L now in Bi_K1, Bi_L1, Bi_L2*/
}
if (teach) {
printf("m = ");
ShowLargeNumber(Bi_H2);
printf("\nn = ");
ShowLargeNumber(Bi_K2);
printf("\nUsing the formulas: P = m\n");
printf("Q = -Cn \n");
if (type == hyperbolic_gen) {
printf("K =CD(P+S-2) + E(B-Bm-2ACn)4AC-B^2\n");
}
printf("R = An \nS = m + Bn\n");
if (type == hyperbolic_gen) {
printf("L =D(B-Bm-2ACn) + AE(P+S-2)4AC - B^2 + Dn\n");
}
printf("we obtain:\n");
}
printf("P = ");
ShowLargeNumber(Bi_H2);
printf("\nQ = ");
MultLargeNumber(-g_C, Bi_K2, Bi_H1); // H1 = -C*K2
ShowLargeNumber(Bi_H1);
if (type == hyperbolic_gen) {
printf("\nK = ");
ShowLargeNumber(Bi_L1);
}
printf("\nR = ");
MultLargeNumber(g_A, Bi_K2, Bi_H1); // H1 = A*K2
ShowLargeNumber(Bi_H1);
printf("\nS = ");
MultAddLargeNumbers(1, Bi_H2, g_B, Bi_K2, Bi_H1);
ShowLargeNumber(Bi_H1);
if (type == hyperbolic_gen) {
printf("\nL = ");
ShowLargeNumber(Bi_L2);
}
putchar('\n');
return 0;
}
/* Sum = Nbr1 +Nbr2 */
void AddLarge(const mpz_t Bi_Nbr1, const mpz_t Bi_Nbr2, mpz_t Bi_Sum) {
mpz_add(Bi_Sum, Bi_Nbr1, Bi_Nbr2);
}
/* dest = Src + Nbr */
void AddLarge(const mpz_t Bi_Src, long long Nbr, mpz_t Bi_Dest) {
mpz_add_si(Bi_Dest, Bi_Src, Nbr);
}
/* called from ShowRecursion
type = hyperbolic_homog (homogenous) or hyperbolic_gen (general hyperbolic)
Uses global variables Bi_H1, Bi_H2, Bi_K2, Bi_L1, Bi_L2, A, B, C, D, E */
void ShowRecursionRoot(equation_class type) {
char t; // 1 if K and L not integers, otherwise 0
t = ShowSols(type);
if (type == hyperbolic_gen) {
ChangeSign(Bi_H2);
ChangeSign(Bi_K2);
if (t == 0) putchar('\n'); /* separate 2 sets of values for P, Q, K, R, S, L
If there is only 1 set we just get an unneeded blank line.*/
//if (t == 1 && ShowSols(type) == 1) {
/* changed this so that ShowSols is called again even if t is 1.
ShowSols has an important side-effect; it prints values for P, Q, K, R, S, L
if it can find them. Sometimes each call produces a different but valid
set of values */
if (ShowSols(type) == 1 && t ==1) {
/* if we get to here we haven't yet got any values for P, Q, K, R, S, L.
The 3rd way below tends to produce very large numbers. */
if (teach) {
printf("m = ");
ShowLargeNumber(Bi_H2);
printf("\nn = ");
ShowLargeNumber(Bi_K2);
std::cout << "\nUsing the formulas: P = m" << sq << " - ACn" << sq <<
" \nQ = -Cn(2m + Bn) \n K = -n(Em + CDn)\n" <<
"R = An(2m + Bn)\nS = m" << sq << " + 2Bmn + (B" + sq << " - AC)n" << sq <<
"\nL = n(Dm + (BD-AE)n) \nwe obtain:\n";
}
Mult2LargeNumbers(Bi_H2, Bi_H2, Bi_H1); /* m^2 */
Mult2LargeNumbers(Bi_H2, Bi_K2, Bi_K1); /* mn */
Mult2LargeNumbers(Bi_K2, Bi_K2, Bi_L1); /* n^2 */
MultAddLargeNumbers(1, Bi_H1, -g_A*g_C, Bi_L1, Bi_L2);
printf("P = ");
ShowLargeNumber(Bi_L2);
MultAddLargeNumbers(-2 * g_C, Bi_K1, -g_B*g_C, Bi_L1, Bi_L2);
printf("\nQ = ");
ShowLargeNumber(Bi_L2);
MultAddLargeNumbers(-g_E, Bi_K1, -g_C*g_D, Bi_L1, Bi_L2);
printf("\nK = ");
ShowLargeNumber(Bi_L2);
MultAddLargeNumbers(2 * g_A, Bi_K1, g_A*g_B, Bi_L1, Bi_L2);
printf("\nR = ");
ShowLargeNumber(Bi_L2);
MultAddLargeNumbers(g_B*g_B - g_A*g_C, Bi_L1, 2 * g_B, Bi_K1, Bi_L2);
AddLarge(Bi_L2, Bi_H1, Bi_L2);
printf("\nS = ");
ShowLargeNumber(Bi_L2);
MultAddLargeNumbers(g_D, Bi_K1, g_B*g_D - g_A*g_E, Bi_L1, Bi_L2);
printf("\nL = ");
ShowLargeNumber(Bi_L2);
putchar('\n');
}
}
}
/* called from solveEquation. Returns true if equation has no solutions*/
bool CheckMod(long long R, long long S, long long X2, long long X1, long long X0) {
long long Y2 = gcd(R, S);
long Y1 = 2;
int indH = 1;
long long D1 = abs(Y2);
long long factors[64];
if (teach) {
if (Y2 != 1) {
printf("We try to check the equation modulo the prime divisors of ");
if (R != 0 && S != 0) {
//w("gcd(" + numToStr(abs(R)) + "," + numToStr(abs(S)) + ") = " + numToStr(Y2) + ".");
printf("gcd(%lld, %lld) = %lld.", R, abs(S), Y2);
}
else {
//w(numToStr(Y2) + ".\n");
printf("%lld. \n", Y2);
}
}
}
/* store factors */
while (D1 >= Y1*Y1) {
int T = 0;
while (D1%Y1 == 0) {
T++;
if (T == 1) {
factors[indH++] = Y1; // only save factor once
}
D1 /= Y1; // remove factor
}
Y1++;
if (Y1>3) {
Y1++; // skip even numbers other than 2
}
}
if (D1>1) {
factors[indH++] = D1;
}
/* now have list of factors. indH is the number of factors*/
for (int T = 1; T<indH; T++) {
if (factors[T]>1) {
long long Z = ((X1*X1 - 4 * X0*X2) % factors[T]) + factors[T];
long long N = (factors[T] - 1) / 2;
long long Y = 1;
while (N != 0) {
if (N % 2 != 0) {
Y = (Y*Z) % factors[T];
}
N /= 2;
Z = (Z*Z) % factors[T];
}
if (Y>1) {
if (teach) {
printf("There are no solutions modulo %lld,", factors[T]);
NoSol();
}
return true; // equation has no solutions
}
}
}
return false; // equation appears to have solution(s)
}
/* reverse sign of Nbr */
void ChSign(mpz_t Dp_Nbr) {
mpz_neg(Dp_Nbr, Dp_Nbr);
}
/* return true iff N1 == N2 */
bool AreEqual(const mpz_t Dp_N1, const mpz_t Dp_N2) {
int rv = mpz_cmp(Dp_N1, Dp_N2);
return (rv == 0);
}
/* return true iff N1 == 0 */
bool IsZero(const mpz_t Dp_N1) {
int rv = mpz_sgn(Dp_N1);
return (rv == 0);
}
bool IsNeg(const mpz_t Dp_N1) {
int rv = mpz_sgn(Dp_N1);
return (rv < 0);
}
/* return true iff A == 1 */
bool IsOne(const mpz_t Dp_A) {
int rv = mpz_cmp_si(Dp_A, 1);
return (rv == 0);
}
/* Diff = Nbr1- Nbr2 */
void SubtDoublePrecLong(const mpz_t Dp_Nbr1, const mpz_t Dp_Nbr2, mpz_t Dp_Diff) {
mpz_sub(Dp_Diff, Dp_Nbr1, Dp_Nbr2);
}
/* convert Nbr to string */
std::string numToStr(const mpz_t Dp_Nbr) {
std::string nbrOutput;
char* buffer = NULL;
// convert to null-terminated ascii string, base 10, with sign if -ve
buffer = mpz_get_str(NULL, 10, Dp_Nbr);
nbrOutput = buffer; // copy from C-style string to STL-type string
free(buffer); // avoid memory leakage
return nbrOutput;
}
/* convert integer to a string */
std::string numToStr(long long num) {
char numbr[21];
sprintf_s(numbr, sizeof(numbr), "%lld", num);
number = numbr; // copy to C++ string
return number;
}
/* print ax^2 +bxy +cy2 (with apppropriate signs)*/
void ShowBigEq(mpz_t Dp_A, mpz_t Dp_B, mpz_t Dp_C, std::string x, std::string y) {
gmp_printf("%Zd%s%s ", Dp_A, x.c_str(), sq.c_str());
if (!IsZero(Dp_B)) {
gmp_printf("%+Zd%s%s ", Dp_B, x.c_str(), y.c_str());
}
if (!IsZero(Dp_C)) {
gmp_printf("%+Zd", Dp_C);
}
if (y.length() == 0)
std::cout << " ";
else
std::cout << " " << y << sq << " ";
}
/* convert biginteger to normal. Checks for overflow */
long long DoublePrecToLong(const mpz_t x) {
long long rv;
assert(mpz_fits_slong_p(x) != 0); // is x too big for normal integer?
rv = mpz_get_si(x); // convert to normal integer
return rv;
}
/* prepare for solving by continued fractions.
return values in global variables Disc, SqrtDisc, Dp_NUM, Dp_DEN */
void GetRoot(mpz_t Dp_A, mpz_t Dp_B, mpz_t Dp_C) {
long long A, B, C, M, P, T, Z;
mpz_t Dp_P, Dp_M, Dp_Z, Dp_G, Dp_K, Dp_zz;
bool NUMis0;
mpz_inits(Dp_P, Dp_M, Dp_Z, Dp_G, Dp_K, Dp_zz, NULL);
A = DoublePrecToLong(Dp_A); // assume that Dp_A will fit int 64 bits
B = DoublePrecToLong(Dp_B);
C = DoublePrecToLong(Dp_C);
g_Disc = B*B - 4 * A*C; // Discriminant = B^2 -4AC
mpz_set(Dp_NUM, Dp_B);
ChSign(Dp_NUM); // NUM = -Dp_B
NUMis0 = IsZero(Dp_NUM); /* check whether NUM == 0 */
AddLarge(Dp_A, Dp_A, Dp_DEN); // DEN = Dp_A*2
if (teach) {
printf("We have to find the continued fraction expansion of the roots of \n");
ShowBigEq(Dp_A, Dp_B, Dp_C, "t", "");
printf("= 0, that is, ");
printf("(Sqrt(%lld) ", g_Disc);
if (!NUMis0) { // print NUM if it's not zero
//w("(Sqrt(" + numToStr(Disc) + ") ");
//printf("(Sqrt(%lld) ", Disc);
gmp_printf("%+Zd) ", Dp_NUM); // print num with sign + or -
}
if (IsNeg(Dp_DEN )) {
std::cout << " / (" << numToStr(Dp_DEN) << ")"; // print /(-den) if negative
}
else {
std::cout << " / " << numToStr(Dp_DEN); // print /den if positive
}
putchar('\n');
}
gcd(Dp_NUM, Dp_DEN, Dp_G); // Dp_G = gcd(NUM,DEN)
Mult2LargeNumbers(Dp_G, Dp_G, Dp_Z); // Dp_Z = Dp_G^2 = gcd(NUM,DEN)^2
LongToDoublePrecLong(g_Disc, Dp_G); // Dp_G = Disc = B^2-4AC
gcd(Dp_Z, Dp_G, Dp_G); // Dp_G = gcd(NUM^2, DEN^2, Disc)
A = DoublePrecToLong(Dp_G); // convert gcd. assume that gcd fit into 64 bits!!
B = 1;
T = 3;
// remove any repeated factors from A (=Dp_G), put sqrt(product of repeated factors) in B
while (A % 4 == 0) {
A /= 4; // remove factor 2^2
B *= 2;
}
while (A >= T*T) {
while (A % (T*T) == 0) {
A /= T*T; // remove factor T^2
B *= T;
}
T += 2;
}
/* B is the product of the factors removed from A (which is the GCD of NUM^2, DEN^2 , Disc)*/
g_Disc /= B*B;
DivLargeNumber(Dp_NUM, B, Dp_NUM); // NUM /= B
DivLargeNumber(Dp_DEN, B, Dp_DEN); // DEN /= B
if (teach && B != 1) {
bool DENis1 = IsOne(Dp_DEN); /* check whether DEN == 1*/
printf("Simplifying, ");
if (!DENis1 && !NUMis0) {
printf("(");
}
//w("Sqrt(" + numToStr(Disc) + ")");
printf("Sqrt(%lld)", g_Disc);
if (!NUMis0) {
gmp_printf("%+Zd", Dp_NUM); // print NUM with sign + or -
}
if (!DENis1) {
if (NUMis0) {
printf(" / ");
}
else {
printf(") / ");
}
}
if (IsNeg(Dp_DEN)) {
std::cout << "(" << numToStr(Dp_DEN) << ")"; // print (-DEN)
}
else {
if (!DENis1) {
std::cout << numToStr(Dp_DEN); // print DEN
}
}
putchar('\n');
}
g_Disc *= B*B;
mpz_set(Dp_NUM, Dp_B); // NUM = B
ChSign(Dp_NUM); // NUM = -B
AddLarge(Dp_A, Dp_A, Dp_DEN); // DEN = A*2
SqrtDisc = llSqrt(g_Disc);
/* temporary */
//std::cout << "**temp** getroot: DP_A=" << numToString(Dp_A);
//std::cout << " DP_B=" << numToString(Dp_B);
//std::cout << " DP_C=" << numToString(Dp_C);
//std::cout << " DP_NUM=" << numToString(Dp_NUM);
//std::cout << " DP_DEN=" << numToString(Dp_NUM);
//std::cout << " SqrtDisc =" << SqrtDisc << " Disc =" << g_Disc << "\n";
/* end temporary */
if (teach) {
printf("The continued fraction expansion is: \n");
mpz_set(Dp_P, Dp_DEN); // P = DEN
/* if DEN >= 0 then K = SqrtDisc else K = SqrtDisc+1 */
LongToDoublePrecLong(SqrtDisc + (IsNeg(Dp_DEN) ? 1 : 0), Dp_K);
AddLarge(Dp_K, Dp_NUM, Dp_K); // K = K+NUM
Z = DivDoublePrec(Dp_K, Dp_DEN); // Z = K/DEN
LongToDoublePrecLong(Z, Dp_M); // M = K/DEN
Mult2LargeNumbers(Dp_M, Dp_DEN, Dp_K); // K = M+DEN
SubtDoublePrecLong(Dp_K, Dp_NUM, Dp_M); // M = K-NUM
//w("" + numToStr(Z));
printf("%lld", Z);
std::string sep = "+ //";
int cont = -1;
B = P = C = M = -1;
while (cont<0 || B != P || C != M) {
std::cout << sep;
sep = ", ";
mpz_add_si(Dp_zz, Dp_M, SqrtDisc);
if (cont<0 &&
/* is P > 0 and P < SqrtDisc+M ?*/
(mpz_cmp(Dp_P, Dp_zz) < 0) &&
(mpz_sgn(Dp_P) > 0) &&
/* is M > 0 and M <= SqrtDisc ?*/
(mpz_cmp_si(Dp_M, SqrtDisc) <= 0) &&
(mpz_sgn(Dp_M) > 0) )
{
putchar('\n');
B = P = DoublePrecToLong(Dp_P);
C = M = DoublePrecToLong(Dp_M);
cont = 0;
}
if (cont >= 0) {
P = (g_Disc - M*M) / P; /* both numerator and denominator are positive */
Z = (SqrtDisc + M) / P;
M = Z*P - M;
cont++;
}
else {
LongToDoublePrecLong(g_Disc, Dp_Z); // Z = Disc
Mult2LargeNumbers(Dp_M, Dp_M, Dp_G); // G = M^2
SubtDoublePrecLong(Dp_Z, Dp_G, Dp_G); // G = Disc-M^2
DivideDoublePrecLong(Dp_G, Dp_P, Dp_K); // K=G/P
mpz_set(Dp_P, Dp_K); // P=K
LongToDoublePrecLong(SqrtDisc + (IsNeg(Dp_P) ? 1 : 0), Dp_Z);
AddLarge(Dp_Z, Dp_M, Dp_K);
Z = DivDoublePrec(Dp_K, Dp_P);
LongToDoublePrecLong(Z, Dp_G);
Mult2LargeNumbers(Dp_G, Dp_P, Dp_Z);
SubtDoublePrecLong(Dp_Z, Dp_M, Dp_M);
}
//w("" + numToStr(Z));
printf("%lld", Z);
}
printf("//\nwhere the periodic part is on 2nd line");
if (cont>1) {
//w(" (the period has " + numToStr(cont) + " coefficients)");
printf(" (the period has %d coefficients)", cont);
}
putchar('\n');
}
mpz_clears(Dp_P, Dp_M, Dp_Z, Dp_G, Dp_K, Dp_zz, NULL);
assert(_CrtCheckMemory());
}
/* return gcd (P,Q,R), unless gcd is not a factor of S.
In this case return 0 */
long long DivideGcd(long long P, long long Q, long long R, long long S,
const std::string x1, const std::string y) {
int t;
long long N = gcd(P, gcd(Q, R));
if (N != 1) {
if (teach) {
printf("We must get the gcd of all terms except the constant: \n");
//w("gcd(" + numToStr(P));
printf("gcg(%lld", P);
if (Q != 0) {
//w(", " + numToStr(Q));
printf(", %lld", Q);
}
if (R != 0) {
//w(", " + numToStr(R));
printf(", %lld", R);
}
//w(") = " + numToStr(N) + "\n");
printf(") = %lld \n", N);
}
if (S%N != 0) {
NoGcd(S);
return 0;
}
if (teach) {
std::cout << divgcd; // show new values after division by gcd
P /= N;
Q /= N;
R /= N;
S /= N;
ShowEq(P, 0, 0, Q, R, S, x1, y);
printf(" = 0 \n");
}
}
if (teach) {
if (abs(R) != 1) {
printf("This means that ");
ShowEq(P, 0, 0, Q, 0, S, x1, y);
//w(" should be a multiple of " + numToStr(abs(R)) + "\n");
printf(" should be a multiple of %lld \n", abs(R));
std::cout << "To determine this, we should try all values of " << x1 << " from 0 to " <<
(abs(R) - 1) << " to check if the condition holds.\n";
t = 0;
for (long long u = 0; u<abs(R); u++) {
if ((P*u*u + Q*u + S) % R == 0) {
if (t != 0) {
std::cout << ", " << u;
}
else {
std::cout << "The values of " << x1 << " (mod " <<
abs(R) << ") are: " << u;
t = 1;
}
}
}
if (t == 0) {
std::cout << "The modular equation is not satisfied by any " << x1;
NoSol();
return 0;
}
putchar('\n');
}
else {
t = 1;
}
}
return N;
}
/* compare 2 Bi numbers*/
int Compare(const mpz_t Bi_array, const mpz_t Bi_K1) {
return mpz_cmp(Bi_array, Bi_K1);
}
int Comparev(const void * Bi_array, const mpz_t Bi_K1) {
mpz_t temp;
memcpy(temp, Bi_array, sizeof(mpz_t));
return mpz_cmp(temp, Bi_K1);
}
/* Insert new number into sorted solutions vector */
/* performing a binary search */
/* called from ShowLargeXY */
/* Note: an mpz_t is in fact a structure which is not a type that is supported
by the std::vector STL so the mpz_t structures and the values they contain are
are copied from the stack to blocks in the heap and the vectors contain pointers
to the copies on the heap. */
void InsertNewSolution(const mpz_t Bi_H1, mpz_t Bi_K1) {
ptrdiff_t indexVector= 0, compare;
size_t sizeVector = 0, increment;
/* temporary */
//gmp_printf("\n**temp InsertNewSolution X = %Zd Y = %Zd\n", Bi_H1, Bi_K1);
/* end temporary */
sizeVector = sortedSolsYv.size();
if (sizeVector > 0) { // is there already something in the list?
increment = 1;
while (increment * 2 <= sizeVector) {
increment *= 2;
}
while (increment > 0) { /* Perform binary search */
if (indexVector + increment <= sizeVector) {
compare = Comparev(sortedSolsXv.at(indexVector + increment - 1), Bi_H1);
if (compare == 0) {
compare = Comparev(sortedSolsYv.at(indexVector + increment - 1), Bi_K1);
}
if (compare == 0) {
/* temporary */
/*printf("** duplicate solution discarded: X = ");
ShowLargeNumber(Bi_H1);
printf(" Y = ");
ShowLargeNumber(Bi_K1);
putchar('\n');*/
/* end temporary */
return; // if solution already in list don't add it again
}