-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhard-level-math.cpp
More file actions
1357 lines (1089 loc) · 41.9 KB
/
hard-level-math.cpp
File metadata and controls
1357 lines (1089 loc) · 41.9 KB
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
// 🔸 1. Advanced Number Theory ⭐⭐⭐
// Euler’s Totient Function (φ(n)) ⭐⭐⭐
// Euler’s Theorem
// Chinese Remainder Theorem ⭐⭐⭐
// Wilson’s Theorem
// 🔸 2. Advanced Modular Arithmetic
// Modular exponentiation with large numbers
// Lucas Theorem ⭐⭐⭐
// Fast nCr for large N
// 🔸 3. Advanced Combinatorics ⭐⭐⭐
// Stars and Bars ⭐⭐⭐
// Catalan Numbers ⭐⭐⭐
// Derangements
// 🔸 4. Matrix Exponentiation ⭐⭐⭐
// Solve recurrence relations
// Fibonacci in log N
// 🔸 5. Probability & Expected Value ⭐⭐⭐
// Basic probability in CP
// Expected value problems
// 🔸 6. Game Theory ⭐⭐⭐
// Grundy numbers
// Nim Game
// 🔸 7. Advanced Techniques
// FFT (Fast Fourier Transform) ⭐⭐⭐
// Polynomial multiplication
// ⭐ 1.1 Euler’s Totient Function φ(n)
// 💡 Concept
// φ(n) = count numbers from 1..n that are coprime with n.
// Example:
// φ(9)=6
// because {1,2,4,5,7,8} are coprime with 9.
// ⚙️ Formula
// For prime factors:
// φ(n) = n * (p1-1)/p1 * (p2-1)/p2 * ... * (pk-1)/pk
//φ(n)=n * Πp|n(1 - 1/p) for all distinct prime factors p of n
// Where p1, p2, ..., pk are the distinct prime factors of n.
// 🧠 Usage
// Count coprime pairs
// RSA encryption
// ⚙️ Algorithm
// Factor n to find distinct primes
// Apply the formula
// Time complexity: O(√n) for factorization, O(k) for applying formula
// Example: φ(10)
// Prime factors: 2, 5
// φ(10) = 10 * (1 - 1/2) * (1 - 1/5) = 10 * (1/2) * (4/5) = 4
// So φ(10) = 4
// Note: For multiple queries, precompute φ(n) for all n up to a limit using a sieve-like method in O(n log log n).
// Example: Precompute φ(n) for n = 1 to 10
// φ(1) = 1
// φ(2) = 1
// φ(3) = 2
// φ(4) = 2
// φ(5) = 4
// φ(6) = 2
// φ(7) = 6
// φ(8) = 4
// φ(9) = 6
// φ(10) = 4
// This matches our earlier calculation for φ(10) = 4
// 🧠 CP Usage
// Euler theorem
// modular inverse
// coprime count
// graph gcd problems
#include<bits/stdc++.h>
using namespace std;
long long phi(int n){
long long res=n;
for(long long i=2;i*i<=n;i++){
if(n%i==0){
while(n%i==0) n/=i;
res-=res/i;
}
}
if(n>1){
res-=res/n;
}
return res;
}
int main(){
int n;
cin>>n;
cout<<phi(n)<<endl;
return 0;
}
// ⭐ 1.2 Euler’s Theorem
// 💡 Formula
// If gcd(a,n)=1:
// a^φ(n) ≡ 1 (mod n)
// Where φ(n) is Euler’s Totient Function.
// 🧠 Use
// Used when modulus is not prime.
// This is generalized Fermat's Little Theorem.
// Example: Compute 3^4 mod 10
// φ(10) = 4 (from previous example)
// Since gcd(3,10)=1, we can use Euler's theorem:
// 3^4 ≡ 1 (mod 10)
// So 3^4 mod 10 = 1
// 🧠 CP Usage
// Modular exponentiation with non-prime moduli
// Modular inverses when modulus is not prime
// Example: Compute modular inverse of 3 mod 10
// Since gcd(3,10)=1, we can use Euler's theorem:
// 3^φ(10) ≡ 1 (mod 10)
// 3^4 ≡ 1 (mod 10)
// To find the modular inverse of 3 mod 10, we can compute 3^(φ(10)-1) mod 10:
// 3^(4-1) ≡ 3^3 ≡ 7 (mod 10)
// So the modular inverse of 3 mod 10 is 7, since (3 * 7) mod 10 = 1
// Note: For large n, precompute φ(n) for all n up to a limit using a sieve-like method in O(n log log n) to efficiently apply Euler's theorem for multiple queries.
// Example: Precompute φ(n) for n = 1 to 10
// φ(1) = 1
// φ(2) = 1
// φ(3) = 2
// φ(4) = 2
// φ(5) = 4
// φ(6) = 2
// φ(7) = 6
// φ(8) = 4
// φ(9) = 6
// φ(10) = 4
#include<bits/stdc++.h>
using namespace std;
long long eulerPhi(int n){
long long res=n;
for(long long i=2;i*i<=n;i++){
if(n%i==0){
while(n%i==0) n/=i;
res-=res/i;
}
}
if(n>1){
res-=res/n;
}
return res;
}
long long modExp(long long a, long long b, int mod) {
long long res = 1;
a = a % mod; // Handle cases where a >= mod
while(b > 0) {
if(b & 1) res = (res * a) % mod; // If b is odd, multiply a with result
a = (a * a) % mod; // Square a
b >>= 1; // Right shift b (divide by 2)
}
return res;
}
int main(){
int n, a, b, mod;
cout << "Enter n for φ(n): ";
cin >> n;
cout << "φ(" << n << ") = " << eulerPhi(n) << endl;
cout << "Enter base, exponent and modulus for modular exponentiation: ";
cin >> a >> b >> mod;
cout << a << " raised to the power " << b << " modulo " << mod << " is: " << modExp(a, b, mod) << endl;
return 0;
}
// 🔶 1) COPRIME COUNT ⭐⭐⭐
// 💡 What is Coprime?
// Two numbers are coprime if:
// gcd(a,b)=1
// Example:
// gcd(8,15)=1
// So 8 and 15 are coprime.
// 🎯 Problem Type
// Count how many numbers from 1..n are coprime with n.
// This is exactly:
// ✅ Euler Totient Function
// // φ(n) = count of numbers from 1..n that are coprime with n.
//formula: φ(n) = n * Πp|n(1 - 1/p) for all distinct prime factors p of n
// 🧠 INTUITION
// Suppose n = 12
// Numbers from 1..12:
// 1 2 3 4 5 6 7 8 9 10 11 12
// Check gcd with 12:
// gcd(1,12)=1 ✅
// gcd(5,12)=1 ✅
// gcd(7,12)=1 ✅
// gcd(11,12)=1 ✅
// So answer = 4
// Thus:
// φ(12)=4
// ⚙️ ALGORITHM
// Prime factorize n.
// For every unique prime p:
// result -= result / p
// 🔶 2) GRAPH GCD PROBLEMS ⭐⭐⭐
// This is a very important advanced pattern.
// 💡 CORE IDEA
// Graph nodes contain values.
// We use GCD relation between connected nodes.
// Usually questions ask:
// path gcd
// gcd of subtree
// maximum gcd path
// count edges where gcd > 1
// graph connectivity using gcd
// 🎯 TYPE A: CONNECT IF GCD > 1
// Very famous OA problem.
// 🧪 Example
// Array:
// [6,10,15,7]
// Make edge if gcd > 1
// Connections
// gcd(6,10)=2 ✅
// gcd(6,15)=3 ✅
// gcd(10,15)=5 ✅
// gcd(7, others)=1 ❌
// Graph:
// 6 --- 10
// \ /
// 15
// 7 isolated
// 🧠 QUESTION
// How many connected components?
// Answer:
// 2
// ⚙️ BRUTE FORCE ALGORITHM
// Try all pairs
// If gcd > 1 connect
// DFS/BFS components
#include<bits/stdc++.h>
using namespace std;
int countComponents(vector<int>& a){
int n=a.size();
vector<vector<int>> adj(n);
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(__gcd(a[i],a[j])>1){
adj[i].push_back(j);
adj[j].push_back(i);
}
}
}
vector<int> vis(n,0);
function<void(int)> dfs = [&](int u){
vis[u]=1;
for(int v:adj[u]){
if(!vis[v]) dfs(v);
}
};
int comp=0;
for(int i=0;i<n;i++){
if(!vis[i]){
comp++;
dfs(i);
}
}
return comp;
}
int main(){
int n;
cout<<"Enter number of elements: ";
cin>>n;
vector<int> a(n);
cout<<"Enter the elements: ";
for(int i=0;i<n;i++) cin>>a[i];
cout<<"Number of connected components: "<<countComponents(a)<<endl;
return 0;
}
// ⭐ 1.3 Chinese Remainder Theorem ⭐⭐⭐
// 💡 Problem Type
// Solve:
// x % 3 = 2
// x % 5 = 3
// x % 7 = 2
// 🧠 Usage
// multiple modular constraints
// cyclic schedules
// clock problems
// distributed hashing
//formula: x = a1*M1*y1 + a2*M2*y2 + ... + ak*Mk*yk where Mi = M/mi and yi is the modular inverse of Mi mod mi
// where M = m1*m2*...*mk
// where mi are the moduli and ai are the remainders
//
// ⚙️ Algorithm
// Extended Euclidean Algorithm to find inverses
// Combine equations iteratively
// Time complexity: O(k^2) for k equations
// Example: Solve x % 3 = 2, x % 5 = 3, x % 7 = 2
// Step 1: Calculate M = 3*5*7 = 105
// Step 2: Calculate Mi = M/mi
// M1 = 105/3 = 35
// M2 = 105/5 = 21
// M3 = 105/7 = 15
// Step 3: Calculate yi such that Mi*yi ≡ 1 (mod mi
// y1: 35*y1 ≡ 1 (mod 3) → y1 = 2
// y2: 21*y2 ≡ 1 (mod 5) → y2 = 1
// y3: 15*y3 ≡ 1 (mod 7) → y3 = 1
// Step 4: Combine results
// x = a1*M1*y1 + a2*M2*y2 + a3*M3*y3
// x = 2*35*2 + 3*21*1 + 2*15*1
// x = 140 + 63 + 30 = 233
// Step 5: Final result
// x % M = 233 % 105 = 23
// So the solution is x = 23
// Note: For large k, consider using a more efficient algorithm or library for CRT to handle multiple equations efficiently.
//input format:
// Enter number of equations: 3
// Enter remainders and moduli:
// Equation 1: x % 3
// Remainder: 2
// Equation 2: x % 5
// Remainder: 3
// Equation 3: x % 7
// Remainder: 2
#include<bits/stdc++.h>
using namespace std;
long long CRT(vector<long long>& rem,vector<long long>& mod){
long long product=1;
for(auto m:mod) product*=m;
long long result=0;
for(int i=0;i<rem.size();i++){
long long Mi=product/mod[i];
long long yi=1;
long long a=Mi,b=mod[i];
long long m0=b,y=0,x=1;
if(b==1) continue;
while(a>1){
long long q=a/b;
long long t=b;
b=a%b,a=t;
t=y;
y=x-q*y;
x=t;
}
result+=(rem[i]*Mi*yi)%product;
}
return result;
}
int main(){
int k;
cout<<"Enter number of equations: ";
cin>>k;
vector<long long> rem(k),mod(k);
cout<<"Enter remainders and moduli:\n";
for(int i=0;i<k;i++){
cout<<"Equation "<<i+1<<": x % ";
cin>>mod[i];
cout<<"Remainder: ";
cin>>rem[i];
}
cout<<"Solution x = "<<CRT(rem,mod)<<endl;// Note: The solution is given modulo the product of the moduli.
return 0;
}
//CRT 2nd method
// ✅ 2) CORRECT CRT FORMULA
// For equations:
// x ≡ r1 (mod m1)
// x ≡ r2 (mod m2)
// ...
// Formula:
//x=summation of (ri * Mi * yi)mod M ,for i=1 to k, where Mi = M/mi and yi is the modular inverse of Mi mod mi, and M = m1*m2*...*mk
// where mi are the moduli and ri are the remainders
// where M = m1*m2*...*mk
// where mi are the moduli and ri are the remainders
//Mi=M/mi
//yi is the modular inverse of Mi mod mi
//yi=Mi^-1 mod mi
// Example: Solve x % 3 = 2, x % 5 = 3, x % 7 = 2
// Step 1: Calculate M = 3*5*7 = 105
// Step 2: Calculate Mi = M/mi
// M1 = 105/3 = 35
// M2 = 105/5 = 21
// M3 = 105/7 = 15
// Step 3: Calculate yi such that Mi*yi ≡ 1 (mod mi)
// y1: 35*y1 ≡ 1 (mod 3) → y1 = 2
// y2: 21*y2 ≡ 1 (mod 5) → y2 = 1
// y3: 15*y3 ≡ 1 (mod 7) → y3 = 1
// Step 4: Combine results
// x = a1*M1*y1 + a2*M2*y2 + a3*M3*y3
// x = 2*35*2 + 3*21*1 + 2*15*1
// x = 140 + 63 + 30 = 233
// Step 5: Final result
// x % M = 233 % 105 = 23
// So the solution is x = 23
// Note: The solution is given modulo the product of the moduli, so the final answer is x = 23 (mod 105).
// Note: For large k, consider using a more efficient algorithm or library for CRT to handle multiple equations efficiently.
#include<bits/stdc++.h>
using namespace std;
long long modInverse(long long a,long long mod){
long long b=mod,u=1,v=0;
while(b){
long long t=a/b;
a-=t*b; swap(a,b);
u-=t*v; swap(u,v);
}
u%=mod;
if(u<0) u+=mod;
return u;
}
long long CRT(vector<long long>& rem, vector<long long>& mod){
long long product=1;
for(auto m:mod) product*=m;
long long result=0;
for(int i=0;i<rem.size();i++){
long long Mi=product/mod[i];
long long yi=modInverse(Mi,mod[i]);
result=(result + rem[i]*Mi%product*yi)%product;
}
return (result+product)%product;
}
int main(){
int k;
cout<<"Enter number of equations: ";
cin>>k;
vector<long long> rem(k),mod(k);
cout<<"Enter modulus and remainder:\n";
for(int i=0;i<k;i++){
cin>>mod[i]>>rem[i];
}
cout<<"Solution x = "<<CRT(rem,mod)<<endl;
}
// ⭐ 1.4 Wilson’s Theorem
// 💡 Formula
// For prime p:
// (p−1)!≡−1(modp)
// 🧠 Use
// primality proofs
// theoretical CP questions
// Rare but powerful.
// Example: Check if 7 is prime using Wilson's theorem
// Calculate (7-1)! = 6! = 720
// Since 720 % 7 = 6 and 6 ≡ -1 (mod 7), 7 is prime.
// Note: Wilson's theorem is not efficient for primality testing for large numbers, but it is a fundamental result in number theory and can be used in theoretical contexts or for small primes.
// Example: Check if 10 is prime using Wilson's theorem
// Calculate (10-1)! = 9! = 362880
// Since 362880 % 10 = 0 and 0 ≢ -1 (mod 10), 10 is not prime.
// Note: For large p, calculating (p-1)! can be computationally expensive, so Wilson's theorem is not practical for primality testing in competitive programming, but it serves as an important theoretical tool in number theory.
// Example: Check if 11 is prime using Wilson's theorem
// Calculate (11-1)! = 10! = 3628800
// Since 3628800 % 11 = 10 and 10 ≡ -1 (mod 11), 11 is prime.
// Note: Wilson's theorem is a fundamental result in number theory that provides a necessary and sufficient
#include<bits/stdc++.h>
using namespace std;
long long WilsonTheorem(int p){
if(p<2) return 0; // Not prime
long long fact=1;
for(int i=2;i<p;i++){
fact=(fact*i)%p;
}
return (fact==p-1) ? 1 : 0; // Returns 1 if prime, else 0
}
int main(){
int n;
cout<<"Enter a number: ";
cin>>n;
if(WilsonTheorem(n)){
cout<<n<<" is a prime number."<<endl;
} else {
cout<<n<<" is not a prime number."<<endl;
}
return 0;
}
// ⭐ 2.1 Large Modular Exponentiation
// Used when exponent itself is huge.
// Use Euler theorem:
// a^b mod m = a^(b mod φ(m)) mod m,
// when coprime.
// Example: Compute 3^100 mod 10
// φ(10) = 4 (from previous example)
// Since gcd(3,10)=1, we can use Euler's theorem:
// 3^100 ≡ 3^(100 mod 4) (mod 10)
// 100 mod 4 = 0
#include<bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7; // Common modulus used in competitive programming
long long modExpEuler(long long a, long long b, int mod) {
long long phi = mod - 1; // φ(mod) for prime mod is mod-1
b = b % phi; // Reduce exponent using Euler's theorem
long long res = 1;
a = a % mod; // Handle cases where a >= mod
while(b > 0) {
if(b & 1) res = (res * a) % mod; // If b is odd, multiply a with result
a = (a * a) % mod; // Square a
b >>= 1; // Right shift b (divide by 2)
}
return res;
}
int main(){
long long a, b;
cout << "Enter base and exponent: ";
cin >> a >> b;
cout << a << " raised to the power " << b << " modulo " << MOD << " is: " << modExpEuler(a, b, MOD) << endl;
return 0;
}
// ⭐ 2.2 Lucas Theorem ⭐⭐⭐
// 💡 Use
// For:
// nCr % p
// where n is huge (10^18).
// ⚙️ Formula
// Lucas Theorem states that for a prime p and non-negative integers n and r:
// nCr % p = Π (niCr_i) % p
// where ni and ri are the digits of n and r in base p representation.
//formula:C(n,r) mod p = Π C(ni,ri) mod p for all digits ni and ri of n and r in base p representation
// where ni and ri are the digits of n and r in base p representation.
// Base p decomposition.
//example: Compute C(10^18, 10^9) mod 7
// Step 1: Convert n and r to base 7
// n = 10^18 in base 7 = 2020202020202020202020
// r = 10^9 in base 7 = 2020202020
// Step 2: Apply Lucas Theorem
// C(10^18, 10^9) mod 7 = Π C(ni, ri) mod 7
// = C(2, 2) * C(0, 0) * C
//(2, 2) * C(0, 0) * C(2, 2) * C(0, 0) * C(2, 2) * C(0, 0) * C(2, 2) * C(0, 0) * C(2, 2) * C(0, 0) mod 7
// = 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 mod 7
// = 1
// So C(10^18, 10^9) mod 7 = 1
// Note: Lucas Theorem is particularly useful for computing binomial coefficients modulo a prime when n is very large, as it breaks down the problem into smaller subproblems based on the base p representation of n and r. This allows for efficient computation even when n is on the order of 10^18, which would be infeasible with direct factorial-based methods.
// Note: For large n and r, precompute factorials and inverse factorials modulo p for all digits up to p-1 to efficiently compute C(ni, ri) mod p for each digit pair in the base p representation of n and r.
// Example: Compute C(10^18, 10^9) mod 7 using precomputation
// Step 1: Precompute factorials and inverse factorials mod 7 for digits 0 to 6
// factorial[0] = 1
// factorial[1] = 1
// factorial[2] = 2
// factorial[3] = 6
// factorial[4] = 24
// factorial[5] = 120
// factorial[6] = 720
// inverse_factorial[0] = 1
// inverse_factorial[1] = 1
// inverse_factorial[2] = 4
// inverse_factorial[3] = 5
// inverse_factorial[4] = 3
// inverse_factorial[5] = 6
// inverse_factorial[6] = 2
// Step 2: Convert n and r to base 7
// n = 10^18 in base 7 = 2020202020202020202020
// r = 10^9 in base 7 = 2020202020
#include<bits/stdc++.h>
using namespace std;
long long modPow(long long a, long long b, int mod) {
long long res = 1;
a = a % mod; // Handle cases where a >= mod
while(b > 0) {
if(b & 1) res = (res * a) % mod;
a = (a * a) % mod;
b >>= 1;
}
return res;
}
long long smallNCR(int n,int r,int p){
if(r>n) return 0;
long long res=1;
for(int i=0;i<r;i++){
res=res*(n-i)%p;
res=res*modPow(i+1,p-2,p)%p;
}
return res;
}
long long lucas(long long n,long long r,int p){
if(r==0) return 1;
return lucas(n/p,r/p,p)*smallNCR((int)(n%p),(int)(r%p),p)%p;
}
int main(){
long long n,r;
int p;
cout<<"Enter n, r and prime modulus p: ";
cin>>n>>r>>p;
cout<<"C("<<n<<","<<r<<") mod "<<p<<" = "<<lucas(n,r,p)<<endl;
return 0;
}
// ⭐ 3.1 Stars and Bars ⭐⭐⭐
// 💡 Problem
// Ways to distribute k identical items into n boxes.
// ⚙️ Formula
// Number of ways = C(n+k-1, k) = C(n+k-1, n-1)
// Where C is the binomial coefficient.
// 🧠 OA Usage
// distribute candies
// partition sums
// string construction
// Example: Distribute 5 identical candies into 3 boxes
// Here, n = 3 (boxes) and k = 5 (candies)
// Number of ways = C(3+5-1, 5) = C(7, 5) = 21
// So there are 21 ways to distribute 5 identical candies into 3 boxes.
// Note: The formula C(n+k-1, k) can be derived using the "stars and bars" combinatorial technique, where we represent the k identical items as stars and the n-1 dividers between boxes as bars. The total number of symbols (stars + bars) is n+k-1, and we need to choose k positions for the stars (or equivalently n-1 positions for the bars) to determine the distribution of items into boxes.
// Example: Distribute 4 identical balls into 2 boxes
// Here, n = 2 (boxes) and k = 4 (balls)
// Number of ways = C(2+4-1, 4) = C(5, 4) = 5
// So there are 5 ways to distribute 4 identical balls into 2 boxes.
#include<bits/stdc++.h>
using namespace std;
long long modPow(long long a, long long b, long long mod) {
long long res = 1;
a = a % mod;
while(b > 0) {
if(b & 1) res = (res * a) % mod;
a = (a * a) % mod;
b >>= 1;
}
return res;
}
long long smallNCR(long long n, long long r, long long p){
if(r > n) return 0;
long long res = 1;
for(long long i = 0; i < r; i++){
res = res * (n - i) % p;
res = res * modPow(i + 1, p - 2, p) % p;
}
return res;
}
long long starsAndBars(int n, int k){
if(n <= 0 || k < 0) return 0;
return smallNCR(n + k - 1, k, 1e9 + 7);
}
int main(){
int n, k;
cout << "Enter number of boxes (n) and items (k): ";
cin >> n >> k;
cout << "Number of ways to distribute " << k << " identical items into " << n << " boxes is: " << starsAndBars(n, k) << endl;
return 0;
}
// ⭐ 3.2 Catalan Numbers ⭐⭐⭐
// 💡 Use
// balanced parentheses
// BST count
// triangulation
// mountain arrays
// ⚙️ Formula
// C(n) = (2n)! / ((n+1)! * n!) = C(2n, n) - C(2n, n-1)
//for n>=0, C(n) = (2n)! / ((n+1)! * n!) = C(2n, n) - C(2n, n-1)
//formula other form: C(n) = C(2n, n) - C(2n, n-1)
//formula other form: C(n) = C(2n, n) / (n + 1)
// Where C is the binomial coefficient.
// Example: Count the number of valid parentheses combinations for n = 3
// Here, n = 3 (pairs of parentheses)
// C(3) = (2*3)! / ((3+1)! * 3!) = 6! / (4! * 3!) = 720 / (24 * 6) = 5
// So there are 5 valid combinations of parentheses for n = 3: "((()))", "(()())", "(())()", "()(())", "()()()"
// Note: Catalan numbers have a wide range of applications in combinatorial mathematics, including counting
// the number of ways to correctly match parentheses, the number of binary search trees with n nodes, the number of ways to triangulate a polygon with n+2 sides, and many other combinatorial structures. The nth Catalan number can be computed efficiently using dynamic programming or by using the formula involving binomial coefficients, as shown above.
// Example: Count the number of binary search trees with n = 4 nodes
// Here, n = 4 (nodes)
// C(4) = (2*4)! / ((4+1)! * 4!) = 8! / (5! * 4!) = 40320 / (120 * 24) = 14
// So there are 14 unique binary search trees that can be formed with 4 nodes.
#include<bits/stdc++.h>
using namespace std;
const long long MOD = 1e9 + 7;
long long modPow(long long a, long long b, long long mod) {
long long res = 1;
a = a % mod;
while(b > 0) {
if(b & 1) res = (res * a) % mod;
a = (a * a) % mod;
b >>= 1;
}
return res;
}
long long modInverseFermat(long long a, long long mod) {
return modPow(a, mod - 2, mod);
}
long long nCr(int n, int r) {
if(r > n) return 0;
long long res = 1;
for(int i = 0; i < r; i++) {
res = res * (n - i) % MOD;
res = res * modInverseFermat(i + 1, MOD) % MOD;
}
return res;
}
long long catalan(int n){
return nCr(2*n,n)*modInverseFermat(n+1,MOD)%MOD;
}
int main(){
int n;
cout << "Enter n for Catalan number: ";
cin >> n;
cout << "The " << n << "th Catalan number is: " << catalan(n) << endl;
return 0;
}
// ⭐ 3.3 Derangements
// 💡 Meaning
// Permutations where no element stays in original position.
// ⚙️ Formula
// D(n)=(n−1)(D(n−1)+D(n−2))
// D(0)=1,D(1)=0
// D(n) = (n-1) * (D(n-1) + D(n-2))
// with base cases D(0) = 1 and D(1) = 0
// Example: Count derangements of 4 items
// D(0) = 1
// D(1) = 0
// D(2) = (2-1) * (D(1) + D(0)) = 1 * (0 + 1) = 1
// D(3) = (3-1) * (D(2) + D(1)) = 2 * (1 + 0) = 2
// D(4) = (4-1) * (D(3) + D(2)) = 3 * (2 + 1) = 9
// So there are 9 derangements of 4 items.
// Note: Derangements are also known as "subfactorials" or "!" (exclamation mark) in combinatorics. The number of derangements of n items can also be computed using the formula D(n) = n! * (1 - 1/1! + 1/2! - 1/3! + ... + (-1)^n/n!), which is derived from the principle of inclusion-exclusion. This formula can be more efficient for large n when implemented with modular arithmetic to avoid overflow issues.
// Example: Count derangements of 5 items using the formula D(n) = n! * (1 - 1/1! + 1/2! - 1/3! + 1/4! - 1/5!)
// D(5) = 5! * (1 - 1/1! + 1/2! - 1/3! + 1/4! - 1/5!)
// D(5) = 120 * (1 - 1 + 0.5 - 0.1666667 + 0.0416667 - 0.0083333)
// D(5) = 120 * (0.375) = 45
// So there are 45 derangements of 5 items.
// 🚀 8) CP / OA USE CASES
// Derangements are common in:
// Secret Santa
// misplaced letters
// hat check problem
// seating arrangement
// permutations with restrictions
// probability problems
#include<bits/stdc++.h>
using namespace std;
long long derangement(int n){
vector<long long> dp(n+1);
dp[0]=1;
dp[1]=0;
for(int i=2;i<=n;i++)
dp[i]=(i-1)*(dp[i-1]+dp[i-2]);
return dp[n];
}
int main(){
int n;
cout<<"Enter number of items: ";
cin>>n;
cout<<"Number of derangements for "<<n<<" items is: "<<derangement(n)<<endl;
return 0;
}
// 🔶 4) MATRIX EXPONENTIATION ⭐⭐⭐
// ⭐ 4.1 Fibonacci in log N
// 💡 Core Matrix
// | F(n) | = | 1 1 |^(n-1) * | F(1) |
// | F(n-1) | | 1 0 | | F(0) |
// Where F(0)=0 and F(1)=1.
// ⚙️ Algorithm
// Define matrix multiplication and exponentiation.
// Use fast exponentiation to compute M^(n-1).
// Example: Compute F(10)
// Step 1: Define the transformation matrix M = | 1 1 |
// | 1 0 |
// Step 2: Compute M^(10-1) = M^9 using fast exponentiation
// M^1 = | 1 1 |
// | 1 0 |
// M^2 = M^1 * M^1 = | 2 1 |
// | 1 0 |
// M^4 = M^2 * M^2 = | 5 3 |
// | 3 2 |
// M^8 = M^4 * M^4 = | 34 21 |
// | 21 13 |
// M^9 = M^8 * M^1 = | 55 34 |
// | 34 21 |
// Step 3: F(10) = M^9[0][0] = 55
// So F(10) = 55
// Note: Matrix exponentiation can be applied to any linear recurrence relation, not just Fibonacci numbers. By defining the appropriate transformation matrix, you can compute the nth term of any linear recurrence in O(log n) time, which is much more efficient than the O(n) time required by naive recursive or iterative methods for large n.
// Example: Compute the nth term of the sequence defined by T(n) = 2*T(n-1) + 3*T(n-2) with T(0) = 1 and T(1) = 2
// Step 1: Define the transformation matrix M = | 2 3 |
// | 1 0 |
// Step 2: Compute M^(n-1) using fast exponentiation
// Step 3: T(n) = M^(n-1)[0][0] * T(1) + M^(n-1)[0][1] * T(0)
// So T(n) can be computed efficiently for large n using matrix exponentiation.
// Note: When implementing matrix exponentiation, be mindful of the size of the numbers involved, as they can grow rapidly. Use modular arithmetic if the problem requires it to keep the numbers manageable and prevent overflow issues. Additionally, ensure that your matrix multiplication and exponentiation functions are optimized for performance, especially when dealing with large matrices or a large number of operations.
// Example: Compute T(10) for the sequence defined by T(n) = 2*T(n-1) + 3*T(n-2) with T(0) = 1 and T(1) = 2
// Step 1: Define the transformation matrix M = | 2 3 |
// | 1 0 |
// Step 2: Compute M^(10-1) = M^9 using fast exponentiation
// M^1 = | 2 3 |
// | 1 0 |
// M^2 = M^1 * M^1 = | 7 6 |
// | 2 3 |
// M^4 = M^2 * M^2 = | 55 42 |
// | 14 9 |
// M^8 = M^4 * M^4 = | 3025 2310 |
// | 770 539 |
// M^9 = M^8 * M^1 = | 11015 6930 |
// | 3025 2310 |
// Step 3: T(10) = M^9[0][0] * T(1) + M^9[0][1] * T(0) = 11015 * 2 + 6930 * 1 = 28960
// So T(10) = 28960
// 🧠 Use
// recurrence DP
// linear recurrence
// Fibonacci
// path counting
#include<bits/stdc++.h>
using namespace std;
struct Matrix{
long long a[2][2];
};
Matrix mul(Matrix x,Matrix y){
Matrix r={0};
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
for(int k=0;k<2;k++)
r.a[i][j]+=x.a[i][k]*y.a[k][j];
return r;
}
Matrix power(Matrix base,long long n){
Matrix res={{{1,0},{0,1}}};
while(n){
if(n&1) res=mul(res,base);
base=mul(base,base);
n>>=1;
}
return res;
}
long long fibonacci(long long n){
if(n==0) return 0;
Matrix F={{{1,1},{1,0}}};
Matrix Fn=power(F,n-1);