-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmatrix.h
1114 lines (944 loc) · 35 KB
/
matrix.h
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
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <initializer_list>
#include <iostream>
#include <algorithm>
#include <stdexcept>
#include <vector>
#include <limits>
#include <compare>
#include <iterator>
#include <string_view>
#include <cmath>
#include <sstream>
#include <iomanip>
#include <complex>
#include <numbers>
#include <array>
#include <cassert>
#include <functional>
constexpr int intPow(int val, size_t exp) {
int result = 1;
while(exp--) {
result *= val;
}
return result;
}
class BigInteger {
private:
using DigitT = int32_t;
using DigitSequence = std::vector<DigitT>;
static const int base_exp = 10;
static const int base_exp_power = 4;
static const DigitT base = intPow(base_exp, base_exp_power);
DigitSequence digits_; // invariant: leading digit isn't zero
enum class SignT {
NEGATIVE = -1,
ZERO = 0,
POSITIVE = 1,
};
SignT sign_ = SignT::ZERO;
private: // sign section
void flipSign() {
sign_ = static_cast<SignT>(-1 * static_cast<int>(sign_));
}
static bool oppositeSigns(SignT sign1, SignT sign2) {
return static_cast<int>(sign1) * static_cast<int>(sign2) == -1;
}
static SignT addSigns(SignT sign1, SignT sign2) {
return sign1 == sign2
? sign1
: static_cast<SignT>(static_cast<int>(sign1) + static_cast<int>(sign2));
}
static SignT mulSigns(SignT sign1, SignT sign2) {
return static_cast<SignT>(static_cast<int>(sign1) * static_cast<int>(sign2));
}
void checkAndProcessDigitsEmptiness() {
if (digits_.empty()) {
sign_ = SignT::ZERO;
}
}
// fft section
static size_t reverseBits(size_t x, size_t modulo) {
size_t x_reversed = 0;
for (size_t bit_i = 0; (modulo >> bit_i) != 1; ++bit_i) {
x_reversed = (x_reversed << 1) | ((x >> bit_i) & 1);
}
return x_reversed;
}
void fft(std::vector<std::complex<long double>>& a, std::complex<long double> w0) {
size_t n = a.size();
for (size_t i = 0; i < n; ++i) {
size_t i_rev = reverseBits(i, n);
assert(i_rev < n);
if (i < i_rev) {
std::swap(a[i], a[i_rev]);
}
}
for (size_t level = 1; (n >> level) != 0; ++level) {
std::complex<long double> w_step = w0;
for (size_t i = 1; (n >> level >> i) != 0; ++i) {
w_step *= w_step;
}
size_t chunk_sz = (1ull << level);
for (size_t chunk_start = 0; chunk_start < n; chunk_start += chunk_sz) {
std::complex<long double> w = 1;
for (size_t offset = 0; offset < (chunk_sz >> 1); ++offset) {
size_t i = chunk_start + offset;
size_t conjugate_i = i + (chunk_sz >> 1);
std::complex<long double> x = a[i ];
std::complex<long double> y = a[conjugate_i];
a[i ] = x + w * y;
a[conjugate_i] = x - w * y;
w *= w_step;
}
}
}
}
void mulPolynoms(std::vector<long double>& lhs, const std::vector<long double>& rhs) {
size_t n = 1;
while (n < std::max(lhs.size(), rhs.size())) {
n <<= 1;
}
n <<= 1;
std::vector<std::complex<long double>> a(n, 0), b(n, 0);
std::copy(lhs.begin(), lhs.end(), a.begin());
std::copy(rhs.begin(), rhs.end(), b.begin());
long double arg = 2 * std::numbers::pi_v<long double> / static_cast<long double>(n);
std::complex<long double> w0(std::cos(arg), std::sin(arg));
fft(a, w0);
fft(b, w0);
for (size_t i = 0; i < n; ++i) {
a[i] *= b[i];
}
fft(a, std::conj(w0));
lhs.resize(n);
for (size_t i = 0; i < n; ++i) {
lhs[i] = a[i].real() / n;
}
}
// digit section
static std::strong_ordering compareDigits(
const DigitSequence& lhs, const DigitSequence& rhs) {
if (lhs.size() != rhs.size()) return lhs.size() <=> rhs.size();
for (size_t digit_i = lhs.size(); digit_i >= 1; --digit_i) {
// for (size_t digit_i = lhs.size(); digit_i-- > 0; ) {
const DigitT& l_digit = lhs[digit_i - 1];
const DigitT& r_digit = rhs[digit_i - 1];
if (l_digit != r_digit) {
return l_digit <=> r_digit;
}
}
return std::strong_ordering::equal;
}
static void deleteLeadingZeros(DigitSequence& digits) {
while (!digits.empty() && digits.back() == 0) {
digits.pop_back();
}
}
static DigitT getDigit(const DigitSequence& digits, size_t i) {
return i >= digits.size() ? 0 : digits[i];
}
void addDigits(DigitSequence& lhs, DigitSequence rhs) {
bool transfer = false;
for (size_t digit_i = 0; digit_i < std::max(lhs.size(), rhs.size()); ++digit_i) {
if (digit_i >= lhs.size()) lhs.push_back(0);
if (digit_i >= rhs.size() && !transfer) break;
DigitT& l_digit = lhs[digit_i];
l_digit += transfer + getDigit(rhs, digit_i);
transfer = l_digit >= base;
l_digit %= base;
}
if (transfer) lhs.push_back(1);
}
static void substractDigits(DigitSequence& lhs, DigitSequence rhs,
bool inverse_substraction = false) {
bool digit_debt = false;
for (size_t digit_i = 0; digit_i < std::max(lhs.size(), rhs.size()); ++digit_i) {
if (digit_i >= lhs.size()) lhs.push_back(0);
if (digit_i >= rhs.size() && !digit_debt) break;
DigitT& l_digit = lhs[digit_i];
DigitT r_digit = getDigit(rhs, digit_i);
if (inverse_substraction) std::swap(l_digit, r_digit);
l_digit -= r_digit + digit_debt;
digit_debt = l_digit < 0;
l_digit = (l_digit + base) % base;
}
deleteLeadingZeros(lhs);
}
static void multiplyDigitsPowerBaseExp(DigitSequence& digits, size_t power) {
if (digits.empty()) return;
digits.insert(digits.begin(), power / base_exp_power, 0);
power %= base_exp_power;
unsigned long long factor = static_cast<unsigned long long>(intPow(base_exp, power));
unsigned long long transfer = 0;
for (size_t digit_i = 0; digit_i < digits.size(); ++digit_i) {
transfer += factor * static_cast<unsigned long long>(digits[digit_i]);
digits[digit_i] = static_cast<DigitT>(transfer % base);
transfer /= base;
}
if (transfer != 0) {
digits.push_back(static_cast<DigitT>(transfer));
}
}
static void divideDigitsPowerBaseExp(DigitSequence& digits, size_t power) {
size_t n_digits_to_delete = std::min(power / base_exp_power, digits.size());
digits.erase(digits.begin(), digits.begin() + static_cast<long long>(n_digits_to_delete));
power %= base_exp_power;
unsigned long long divider = static_cast<unsigned long long>(intPow(base_exp, power));
for (size_t digit_i = 0; digit_i < digits.size(); ++digit_i) {
if (digit_i != 0) {
digits[digit_i - 1] += static_cast<DigitT>((static_cast<unsigned long long>(digits[digit_i]) % divider) * (base / divider));
}
digits[digit_i] /= static_cast<DigitT>(divider);
}
deleteLeadingZeros(digits);
}
static void divDigits(DigitSequence& lhs, DigitSequence rhs, bool modulo) {
size_t result_power_base_exp = base_exp_power * (lhs.size() - std::min(lhs.size(), rhs.size()) + 1);
multiplyDigitsPowerBaseExp(rhs, result_power_base_exp);
DigitSequence result;
while (result_power_base_exp--) {
divideDigitsPowerBaseExp(rhs, 1);
multiplyDigitsPowerBaseExp(result, 1);
while (compareDigits(lhs, rhs) >= 0) {
if (result.empty()) {
result.push_back(0);
}
++result.front();
substractDigits(lhs, rhs);
}
}
deleteLeadingZeros(result);
if (!modulo) {
std::swap(lhs, result);
}
}
void mulDigits(DigitSequence& lhs, const DigitSequence& rhs) {
std::vector<long double> l_poly(lhs.begin(), lhs.end());
std::vector<long double> r_poly(rhs.begin(), rhs.end());
mulPolynoms(l_poly, r_poly);
unsigned long long transfer = 0;
for (size_t i = 0; i < l_poly.size(); ++i) {
if (i >= lhs.size()) lhs.push_back(0);
transfer += static_cast<unsigned long long>(std::round(l_poly[i]));
lhs[i] = static_cast<DigitT>(transfer % base);
transfer /= base;
}
while (transfer != 0) {
lhs.push_back(static_cast<DigitT>(transfer % base));
transfer /= base;
}
deleteLeadingZeros(lhs);
}
public:
BigInteger(): sign_(SignT::ZERO) {}
BigInteger(long long x)
: sign_(x == 0 ? SignT::ZERO :
x < 0 ? SignT::NEGATIVE :
SignT::POSITIVE )
{
x = std::abs(x);
while (x != 0) {
digits_.push_back(static_cast<DigitT>(x % base));
x /= base;
}
}
BigInteger(std::string_view str) {
while (!str.empty() && str.front() == '0') {
str.remove_prefix(1);
}
if (str.empty()) {
sign_ = SignT::ZERO;
} else if (str.front() == '-') {
sign_ = SignT::NEGATIVE;
str.remove_prefix(1);
} else {
sign_ = SignT::POSITIVE;
}
//
while (!str.empty()) {
size_t chunk_size = std::min(static_cast<size_t>(base_exp_power), str.size());
std::string_view digit_token = str.substr(str.size() - chunk_size, chunk_size);
str.remove_suffix(chunk_size);
digits_.push_back(static_cast<DigitT>(std::stoll(std::string(digit_token))));
}
}
std::strong_ordering operator<=>(const BigInteger& rhs) const {
if (sign_ != rhs.sign_) {
return sign_ <=> rhs.sign_;
}
return sign_ == SignT::POSITIVE
? compareDigits(digits_ , rhs.digits_)
: compareDigits(rhs.digits_, digits_);
}
bool operator==(const BigInteger& rhs) const = default;
BigInteger& operator+=(const BigInteger& rhs) {
if (oppositeSigns(sign_, rhs.sign_)) {
flipSign();
operator-=(rhs);
flipSign();
return *this;
}
addDigits(digits_, rhs.digits_);
sign_ = addSigns(sign_, rhs.sign_);
return *this;
}
BigInteger& operator-=(const BigInteger& rhs) {
if (oppositeSigns(sign_, rhs.sign_)) {
flipSign();
operator+=(rhs);
flipSign();
return *this;
}
sign_ = addSigns(sign_, rhs.sign_);
bool inverse_substraction = compareDigits(digits_, rhs.digits_) < 0;
substractDigits(digits_, rhs.digits_, inverse_substraction);
checkAndProcessDigitsEmptiness();
if (inverse_substraction) flipSign();
return *this;
}
BigInteger& operator *=(const BigInteger& rhs) {
sign_ = mulSigns(sign_, rhs.sign_);
mulDigits(digits_, rhs.digits_);
return *this;
}
BigInteger& operator /=(const BigInteger& rhs) {
sign_ = mulSigns(sign_, rhs.sign_);
divDigits(digits_, rhs.digits_, false);
checkAndProcessDigitsEmptiness();
return *this;
}
BigInteger& operator %=(const BigInteger& rhs) {
divDigits(digits_, rhs.digits_, true);
checkAndProcessDigitsEmptiness();
return *this;
}
std::string toString() const {
std::ostringstream result;
result << (sign_ == SignT::ZERO ? "0" :
sign_ == SignT::NEGATIVE ? "-" :
"" );
for (size_t i = digits_.size(); i >= 1; --i) {
if (i != digits_.size()) {
result << std::setfill('0') << std::setw(base_exp_power);
}
result << digits_[i - 1];
}
return result.str();
}
BigInteger operator-() const {
BigInteger result = *this;
result.flipSign();
return result;
}
BigInteger& operator++() {
return *this += 1;
}
BigInteger operator++(int) {
BigInteger result = *this;
*this += 1;
return result;
}
BigInteger& operator--() {
return *this -= 1;
}
BigInteger operator--(int) {
BigInteger result = *this;
*this -= 1;
return result;
}
explicit operator bool() const {
return sign_ != SignT::ZERO;
}
BigInteger& multiplyPowerBaseExp(size_t power) {
multiplyDigitsPowerBaseExp(digits_, power);
return *this;
}
};
BigInteger operator+(BigInteger lhs, const BigInteger& rhs) {
return lhs += rhs;
}
BigInteger operator-(BigInteger lhs, const BigInteger& rhs) {
return lhs -= rhs;
}
BigInteger operator*(BigInteger lhs, const BigInteger& rhs) {
return lhs *= rhs;
}
BigInteger operator/(BigInteger lhs, const BigInteger& rhs) {
return lhs /= rhs;
}
BigInteger operator%(BigInteger lhs, const BigInteger& rhs) {
return lhs %= rhs;
}
std::ostream& operator<<(std::ostream& output, const BigInteger& bi) {
return output << bi.toString();
}
std::istream& operator>>(std::istream& input, BigInteger& bi) {
std::string str;
input >> str;
bi = BigInteger(str);
return input;
}
BigInteger operator"" _bi(unsigned long long x) {
return BigInteger(static_cast<long long>(x));
}
BigInteger abs(BigInteger x) {
return x < 0 ? -x : x;
}
BigInteger gcd(BigInteger x, BigInteger y) {
if (y == 0) {
return x;
}
return gcd(y, x % y);
}
class Rational {
private:
BigInteger numerator_ = 0, denominator_ = 1; // invariant: denominator > 0
void normalizeFraction() {
if (denominator_ < 0) {
numerator_ = -numerator_;
denominator_ = -denominator_;
}
BigInteger common_divisor = gcd(abs(numerator_), denominator_);
numerator_ /= common_divisor;
denominator_ /= common_divisor;
}
public:
Rational() {}
Rational(const BigInteger& numerator, const BigInteger& denominator)
: numerator_(numerator), denominator_(denominator) {
normalizeFraction();
}
Rational(BigInteger x): Rational(x, 1) {}
Rational(int x): Rational(x, 1) {};
Rational& operator+=(const Rational& that) {
numerator_ *= that.denominator_;
numerator_ += that.numerator_ * denominator_;
denominator_ *= that.denominator_;
normalizeFraction();
return *this;
}
Rational& operator-=(const Rational& that) {
numerator_ *= that.denominator_;
numerator_ -= that.numerator_ * denominator_;
denominator_ *= that.denominator_;
normalizeFraction();
return *this;
}
Rational& operator*=(const Rational& that) {
numerator_ *= that.numerator_;
denominator_ *= that.denominator_;
normalizeFraction();
return *this;
}
Rational& operator/=(const Rational& that) {
numerator_ *= that.denominator_;
denominator_ *= that.numerator_;
normalizeFraction();
return *this;
}
Rational operator-() const {
return Rational(-numerator_, denominator_);
}
std::strong_ordering operator<=>(const Rational& that) const {
return numerator_ * that.denominator_ <=> that.numerator_ * denominator_;
}
bool operator==(const Rational& that) const = default;
std::string toString() const {
std::string result = numerator_.toString();
if (denominator_ != 1) {
result += '/' + denominator_.toString();
}
return result;
}
std::string asDecimal(size_t precision = 0) const {
BigInteger value = abs(numerator_);
value.multiplyPowerBaseExp(precision);
value /= denominator_;
std::string result = value.toString();
if (result.size() < precision + 1) {
result.insert(0, precision + 1 - result.size(), '0');
}
result.insert(result.end() - static_cast<long long>(precision), '.');
//while (result.back() == '0') {
// result.pop_back();
//}
//if (result.back() == '.') {
// result.pop_back();
//}
if (numerator_ < 0) {
result.insert(0, "-");
}
//if (result.empty() || result.front() == '.') {
// result.insert(result.begin(), '0');
//}
return result;
}
explicit operator double() const {
static const int precision = std::numeric_limits<double>::digits * 10;
return std::stod(asDecimal(precision));
}
};
Rational operator+(Rational lhs, const Rational& rhs) {
return lhs += rhs;
}
Rational operator-(Rational lhs, const Rational& rhs) {
return lhs -= rhs;
}
Rational operator*(Rational lhs, const Rational& rhs) {
return lhs *= rhs;
}
Rational operator/(Rational lhs, const Rational& rhs) {
return lhs /= rhs;
}
std::ostream& operator<<(std::ostream& output, const Rational& rational) {
return output << rational.toString();
}
std::istream& operator>>(std::istream& input, Rational& rational) {
int x = 0;
input >> x;
rational = x;
return input;
}
namespace {
template<size_t N, size_t potential_divider, bool done>
struct IsPrimeHelper {
static const size_t next_potential_divider = potential_divider + 1;
static const size_t next_potential_divider_square = next_potential_divider * next_potential_divider;
static const bool next_done = (next_potential_divider_square > next_potential_divider)
&& (next_potential_divider_square <= N);
static const bool current_check = N % potential_divider != 0;
static const bool next_checks = IsPrimeHelper<N, next_potential_divider, next_done>::value;
static const bool value = current_check && next_checks;
};
template<size_t N, size_t potential_divider>
struct IsPrimeHelper<N, potential_divider, true> {
static const bool value = N != 1;
};
template<size_t N, size_t current_rounding_result, bool done>
struct RoundToPowerOfTwoHelper {
static const size_t next_rounding_result = 2 * current_rounding_result;
static const size_t value = RoundToPowerOfTwoHelper<N, next_rounding_result, (next_rounding_result >= N)>::value;
};
template<size_t N, size_t current_rounding_result>
struct RoundToPowerOfTwoHelper<N, current_rounding_result, true> {
static const size_t value = current_rounding_result;
};
}
template<size_t N>
struct IsPrime {
static const bool value = IsPrimeHelper<N, 2, 2 * 2 <= N>::value;
};
template<size_t N>
const bool is_prime_v = IsPrime<N>::value;
template<size_t N>
struct RoundToPowerOfTwo {
static const size_t value = RoundToPowerOfTwoHelper<N, 1, (1 >= N)>::value;
};
template<size_t N>
const size_t round_to_power_of_two_v = RoundToPowerOfTwo<N>::value;
template<size_t M, size_t N, size_t K>
struct MaxOfThree {
static const size_t value = std::max(std::max(M, N), K);
};
template<size_t M, size_t N, size_t K>
const size_t max_of_three_v = MaxOfThree<M, N, K>::value;
template<size_t N>
class Residue {
private:
size_t value_ = 0;
static size_t sum(size_t lhs, size_t rhs) {
lhs += rhs;
if (lhs < rhs || lhs >= N) {
lhs -= N;
}
return lhs;
}
static size_t mul(size_t lhs, size_t rhs) {
// Implementation isn't trivial since lhs * rhs may simply be
// greater that maximum value of size_t
size_t result = 0;
size_t addition = lhs;
for (size_t factor = rhs; factor != 0; factor >>= 1) {
if (factor & 1) {
result = sum(result, addition);
}
addition = sum(addition, addition);
}
return result;
}
static size_t oppositeByAddition(size_t value) {
return value == 0 ? 0 : N - value;
}
static size_t power(size_t value, size_t power_value) {
if (power_value == 0) {
return 1;
}
size_t power_half = power(value, power_value >> 1);
size_t power_half_square = mul(power_half, power_half);
return mul(power_half_square, power_value & 1 ? value : 1);
}
static size_t inverseByMultiplication(size_t value) {
return power(value, N - 2);
}
static size_t calculateDeduction(int value) {
size_t abs_deduction = std::abs(value) % N;
return value < 0 ? N - abs_deduction : abs_deduction;
}
public:
Residue(int value = 0): value_(calculateDeduction(value)) {}
Residue& operator+=(const Residue& that) {
value_ = sum(value_, that.value_);
return *this;
}
Residue& operator-=(const Residue& that) {
value_ = sum(value_, oppositeByAddition(that.value_));
return *this;
}
Residue& operator*=(const Residue& that) {
value_ = mul(value_, that.value_);
return *this;
}
Residue& operator/=(const Residue& that) {
static_assert(is_prime_v<N>, "Division by modulo that isn't prime");
return operator*=(inverseByMultiplication(that.value_));
}
explicit operator int() const {
return static_cast<int>(value_);
}
explicit operator size_t() const {
return value_;
}
bool operator==(const Residue&) const = default;
};
template<size_t N>
Residue<N> operator+(const Residue<N>& lhs, const Residue<N>& rhs) {
Residue<N> result = lhs;
return result += rhs;
}
template<size_t N>
Residue<N> operator-(const Residue<N>& lhs, const Residue<N>& rhs) {
Residue<N> result = lhs;
return result -= rhs;
}
template<size_t N>
Residue<N> operator*(const Residue<N>& lhs, const Residue<N>& rhs) {
Residue<N> result = lhs;
return result *= rhs;
}
template<size_t N>
Residue<N> operator/(const Residue<N>& lhs, const Residue<N>& rhs) {
Residue<N> result = lhs;
return result /= rhs;
}
template<size_t N>
std::ostream& operator<<(std::ostream& output, const Residue<N>& residue) {
return output << static_cast<size_t>(residue);
}
template<size_t M, size_t N, typename Field>
class Matrix;
template<size_t M, size_t N, size_t K, typename Field>
Matrix<M, K, Field> operator*(const Matrix<M, N, Field>&, const Matrix<N, K, Field>&);
template<size_t M, size_t N, typename Field=Rational>
class Matrix {
private:
std::array<std::array<Field, N>, M> elements_{};
public:
Matrix() {}
Matrix(std::initializer_list<std::initializer_list<Field>> elements) {
size_t row_i = 0;
for (const std::initializer_list<Field>& row: elements) {
size_t col_i = 0;
for (const Field& element : row) {
elements_[row_i][col_i] = element;
++col_i;
}
++row_i;
}
}
void dumpTo(std::ostream& output) const {
forEachCell(*this, [&output](const Field& cell, size_t, size_t col) {
if (col != 0) {
output << " ";
}
output << cell;
if (col == N - 1) {
output << '\n';
}
});
}
static Matrix Identity() {
Matrix result;
return forEachCell(result, [](Field& cell, size_t row, size_t col) {
cell = Field(row == col);
});
}
using CellProcessor = std::function<void (Field& cell, size_t row, size_t col)>;
static Matrix& forEachCell(Matrix& matrix, const CellProcessor& cell_processor) {
for (size_t row = 0; row < M; ++row) {
for (size_t col = 0; col < N; ++col) {
cell_processor(matrix[row][col], row, col);
}
}
return matrix;
}
using ConstantCellProcessor = std::function<void (const Field&, size_t, size_t)>;
static const Matrix& forEachCell(const Matrix& matrix, const ConstantCellProcessor& cell_processor) {
for (size_t row = 0; row < M; ++row) {
for (size_t col = 0; col < N; ++col) {
cell_processor(matrix[row][col], row, col);
}
}
return matrix;
}
using RowSubstractor = std::function<void (Matrix&,
size_t row_destination, size_t row_source, Field substraction_coefficient)>;
using RowSwapper = std::function<void (Matrix&, size_t row1, size_t row2)>;
using RowMultiplicator = std::function<void (Matrix&, size_t row, const Field& coefficient)>;
static void substractRow(Matrix& matrix,
size_t row_destination, size_t row_source, Field substraction_coefficient) {
for (size_t col = 0; col < N; ++col) {
matrix[row_destination][col] -= substraction_coefficient * matrix[row_source][col];
}
}
static void swapRows(Matrix& matrix, size_t row1, size_t row2) {
std::swap(matrix[row1], matrix[row2]);
}
static void multiplyRow(Matrix& matrix, size_t row, const Field& coefficient) {
for (Field& row_element : matrix[row]) {
row_element *= coefficient;
}
}
static Matrix& GaussMethod(Matrix& matrix,
const RowSubstractor& row_substractor,
const RowSwapper& row_swapper,
const RowMultiplicator& row_multiplicator) {
size_t leader_row = 0;
for (size_t col = 0; leader_row < M && col < N; ++col) {
for (size_t row = leader_row; row < M; ++row) {
if (matrix[row][col] != Field(0)) {
row_swapper(matrix, leader_row, row);
break;
}
}
if (matrix[leader_row][col] == Field(0)) {
continue;
}
row_multiplicator(matrix, leader_row, Field(1) / matrix[leader_row][col]);
for (size_t row = 0; row < M; ++row) {
if (row != leader_row) {
row_substractor(matrix, row, leader_row, matrix[row][col]);
}
}
++leader_row;
}
return matrix;
}
using RowT = std::array<Field, N>;
using ColT = std::array<Field, M>;
static bool isZeroRow(const RowT& row) {
return std::all_of(row.begin(), row.end(),
[](const Field& row_element) { return row_element == 0; });
}
Matrix& operator+=(const Matrix& that) {
return forEachCell(*this, [&that](Field& cell, size_t row, size_t col) {
cell += that[row][col];
});
}
Matrix& operator-=(const Matrix& that) {
return forEachCell(*this, [&that](Field& cell, size_t row, size_t col) {
cell -= that[row][col];
});
}
Matrix& operator*=(const Matrix& that) {
return *this = (*this * that);
}
Matrix& operator*=(Field coefficient) {
return forEachCell(*this, [&coefficient](Field& cell, size_t, size_t) {
cell *= coefficient;
});
}
RowT& operator[](size_t row_i) {
return elements_[row_i];
}
const RowT& operator[](size_t row_i) const {
return elements_[row_i];
}
Field det() const {
static_assert(M == N, "Unable to calculate determinant of nonsquare matrix");
Field result = 1;
Matrix tmp = *this;
RowSwapper row_swapper = [&result](Matrix& matrix, size_t row1, size_t row2) {
swapRows(matrix, row1, row2);
if (row1 != row2) {
result *= Field(-1);
}
};
RowMultiplicator row_multiplicator = [&result](Matrix& matrix,
size_t row, Field coefficient) {
multiplyRow(matrix, row, coefficient);
result /= coefficient;
};
GaussMethod(tmp, substractRow, row_swapper, row_multiplicator);
return isZeroRow(tmp.getRow(N - 1)) ? 0 : result;
}
struct InversionError: public std::logic_error {
using std::logic_error::logic_error;
};
Matrix& invert() {
static_assert(M == N, "Unable to invert nonsquare matrix");
Matrix result = Identity();
RowSubstractor row_substractor = [&result](Matrix& matrix, size_t row_destination, size_t row_source, Field coefficient) {
substractRow(matrix, row_destination, row_source, coefficient);
substractRow(result, row_destination, row_source, coefficient);
};
RowSwapper row_swapper = [&result](Matrix& matrix, size_t row1, size_t row2) {
swapRows(matrix, row1, row2);
swapRows(result, row1, row2);
};
RowMultiplicator row_multiplicator = [&result](Matrix& matrix, size_t row, Field coefficient) {
multiplyRow(matrix, row, coefficient);
multiplyRow(result, row, coefficient);
};
GaussMethod(*this, row_substractor, row_swapper, row_multiplicator);
if (isZeroRow(getRow(N - 1))) {
throw InversionError("Inversion of degenerate matrix");
}
return *this = result;
}
Matrix inverted() const {
Matrix result = *this;
return result.invert();
}
size_t rank() const {
Matrix tmp = *this;
GaussMethod(tmp, substractRow, swapRows, multiplyRow);
return static_cast<size_t>(
std::count_if(tmp.elements_.begin(), tmp.elements_.end(),
[](const RowT& row) { return !isZeroRow(row); }));
}
Matrix<N, M, Field> transposed() const {
Matrix<N, M, Field> result;
forEachCell(*this, [&result](const Field& cell, size_t row, size_t col) {
result[col][row] = cell;
});
return result;
}
RowT getRow(size_t row) const {
return operator[](row);
}
ColT getColumn(size_t col) const {
return transposed().getRow(col);
}
bool validIndices(size_t row, size_t col) const {
return row < M && col < N;
}
bool operator==(const Matrix&) const = default;
Field trace() const {
static_assert(M == N, "Unable to calculate a trace of nonsquare matrix");
Field result = 0;
for (size_t i = 0; i < M; ++i) {
result += (*this)[i][i];
}
return result;
}