-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.xml
More file actions
1300 lines (1287 loc) · 153 KB
/
index.xml
File metadata and controls
1300 lines (1287 loc) · 153 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
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title></title>
<link>/</link>
<atom:link href="/index.xml" rel="self" type="application/rss+xml" />
<description></description>
<generator>Hugo Blox Builder (https://hugoblox.com)</generator><language>en-us</language><lastBuildDate>Sun, 02 Feb 2025 12:00:00 +0000</lastBuildDate>
<image>
<url>/media/icon_hu_43cf117bf1a42c34.png</url>
<title></title>
<link>/</link>
</image>
<item>
<title>From Oberon to Go: A Short Family Tree</title>
<link>/post/oberon-to-golang/</link>
<pubDate>Sun, 02 Feb 2025 12:00:00 +0000</pubDate>
<guid>/post/oberon-to-golang/</guid>
<description><p>A compact overview of the Oberon family of languages and how their ideas lead to Go. The lineage runs from Pascal and Modula-2 through Oberon and its variants to Go, with shared emphasis on simplicity, strong typing, and clear semantics.</p>
<h2 id="oberon-1986--niklaus-wirth--jurg-gutknecht">Oberon (1986) — Niklaus Wirth &amp; Jurg Gutknecht</h2>
<ul>
<li>Evolved from Pascal and Modula-2; designed for simplicity and efficiency.</li>
<li>Strong typing, modular programming, integrated development environment.</li>
<li>Used in software and hardware (e.g. Ceres workstation); part of Project Oberon at ETH Zurich.</li>
</ul>
<h2 id="oberon-2-1991--hanspeter-mössenböck">Oberon-2 (1991) — Hanspeter Mössenböck</h2>
<ul>
<li>Extension of Oberon with object-oriented features.</li>
<li>Type-bound procedures, read-only export of variables and methods.</li>
<li>Improved type safety and reusability.</li>
</ul>
<h2 id="modula-3-1988--luca-cardelli-james-donahue-greg-nelson-paul-rovner-andrew-birrell">Modula-3 (1988) — Luca Cardelli, James Donahue, Greg Nelson, Paul Rovner, Andrew Birrell</h2>
<ul>
<li>Evolution of Modula-2: simplicity, safety, systems programming.</li>
<li>Garbage collection, exception handling, strong type system with modules.</li>
<li>Concurrency and generic programming.</li>
</ul>
<h2 id="active-oberon-1997--jurg-gutknecht">Active Oberon (1997) — Jurg Gutknecht</h2>
<ul>
<li>Extends Oberon with active objects and concurrency.</li>
<li>Combines object-oriented and system-programming features.</li>
<li>Runtime and language support for concurrent processes.</li>
</ul>
<h2 id="zonnon-2005--jurg-gutknecht">Zonnon (2005) — Jurg Gutknecht</h2>
<ul>
<li>Draws on Oberon, Active Oberon, and Modula-2.</li>
<li>Component-oriented programming, concurrency and parallelism.</li>
<li>Refined syntax and semantics.</li>
</ul>
<h2 id="oberon-07-2007--niklaus-wirth">Oberon-07 (2007) — Niklaus Wirth</h2>
<ul>
<li>Simplified, modernized Oberon.</li>
<li>Removed deprecated features; clearer syntax and safer semantics.</li>
<li>Streamlined compiler and language report.</li>
</ul>
<h2 id="component-pascal-1997">Component Pascal (1997)</h2>
<ul>
<li><strong>Clemens Szyperski:</strong> Component Pascal at Oberon Microsystems (1991–1997); component-based software; author of <em>Component Software: Beyond Object-Oriented Programming</em>.</li>
<li><strong>K. John Gough:</strong> Co-developed Gardens Point Component Pascal for .NET.</li>
</ul>
<p>Derived from Oberon-2 with stronger object-oriented and component-oriented features; designed for component-based software engineering and .NET integration (Gardens Point).</p>
<h2 id="go--robert-griesemer-rob-pike-ken-thompson">Go — Robert Griesemer, Rob Pike, Ken Thompson</h2>
<ul>
<li>Designed at Google (from 2007); open-sourced 2009, first stable release 2012.</li>
<li>Influenced by the simplicity and efficiency of Oberon and the Wirth tradition.</li>
<li>Targets multicore and networked systems: goroutines, channels, fast compilation.</li>
<li>Garbage-collected, statically typed, simple syntax.</li>
</ul>
<h2 id="how-it-connects">How it connects</h2>
<ul>
<li><strong>Simplicity and efficiency:</strong> Go inherits Oberon’s focus on clear, maintainable code.</li>
<li><strong>Concurrency:</strong> Builds on ideas from Modula-3 and Active Oberon.</li>
<li><strong>Type safety:</strong> Strong static typing throughout the family.</li>
<li><strong>Components:</strong> Component Pascal’s component-oriented design is part of the same design culture.</li>
<li><strong>Implementation and runtimes:</strong> Work on JIT and dynamic optimization (e.g. Michael Franz) influenced modern compilers and runtimes; Go prioritizes fast compilation and efficient execution in that spirit.</li>
</ul>
</description>
</item>
<item>
<title>From Oberon to Go in Faces</title>
<link>/post/oberon-in-faces/</link>
<pubDate>Sat, 01 Feb 2025 12:00:00 +0000</pubDate>
<guid>/post/oberon-in-faces/</guid>
<description><p>Short portraits of people in the Oberon and Modula lineage—language designers, compiler writers, and researchers—whose work leads, in spirit or in person, toward Go.</p>
<p><strong>Niklaus Wirth</strong><br>
Inventor of Pascal (1970), Modula-2 (1978), and Oberon (1986). He also designed Oberon-07 (2007). His work stressed simplicity and efficiency and influenced many modern languages.</p>
<p><strong>Hanspeter Mössenböck</strong><br>
Developed Oberon-2 (1991) and the compiler generator Coco/R. His work on compiler construction and development tools has had a lasting impact.</p>
<p><strong>Jurg Gutknecht</strong><br>
Co-developer of Oberon. Designed Active Oberon (1997) and Zonnon (2005), extending the Oberon family and exploring concurrency and new language paradigms.</p>
<p><strong>Michael Franz</strong><br>
His 1994 PhD thesis was on code generation on the fly. He pioneered techniques in just-in-time (JIT) compilation and dynamic optimization that influenced modern runtimes and language implementations.</p>
<p><strong>Clemens Szyperski</strong><br>
Worked on Component Pascal at Oberon Microsystems (1991–1997). His PhD focused on object-orientation in operating systems. He is known for component-based software engineering and the book <em>Component Software: Beyond Object-Oriented Programming</em>.</p>
<p><strong>Cuno Pfister</strong><br>
Known for embedded systems and the Internet of Things (IoT). He has authored books and developed tools and frameworks in these areas.</p>
<p><strong>Josef Templ</strong><br>
His PhD thesis focused on metaprogramming in Oberon, contributing to the use of metaprogramming techniques in practice.</p>
<p><strong>Ralph Sommerer</strong><br>
His PhD addressed integrating online documents. He developed Oberon Script—a lightweight compiler and runtime that compiles Oberon to JavaScript for interactive web clients (e.g. JMLC 2006).</p>
<p><strong>K. John Gough</strong><br>
Co-developed Gardens Point Component Pascal for .NET, enabling Component Pascal on the .NET framework.</p>
<p><strong>J. Stanley Warford</strong><br>
Known for computer science education, especially his textbooks on computer architecture and assembly language.</p>
<p><strong>Michael Spivey</strong><br>
Known for the Oxford Oberon-2 compiler, contributing to the development and optimization of Oberon-2.</p>
<p><strong>Luca Cardelli, James Donahue, Greg Nelson, Paul Rovner, Andrew Birrell</strong><br>
Designers of Modula-3 (1988), an evolution of Modula-2 emphasizing simplicity, safety, systems programming, and generics.</p>
<p><strong>Robert Griesemer</strong><br>
Co-designer of Go at Google. His PhD focused on programming languages for vector computers. Go is influenced by Oberon’s simplicity and efficiency and is widely used for its performance and concurrency support, continuing the Wirth tradition.</p>
</description>
</item>
<item>
<title>Solving a Three-Variable Recursion via Generating Functions</title>
<link>/post/three-var-recursive/</link>
<pubDate>Tue, 10 Apr 2018 03:14:00 +0000</pubDate>
<guid>/post/three-var-recursive/</guid>
<description><p>This post extends the generating-function technique from the <a href="/post/two-var-recursive-func/">two-variable recursion</a> to a three-variable case. I originally wrote this as an answer to a <a href="https://math.stackexchange.com/questions/1093271/how-to-solve-this-multivariable-recursion/2730331#2730331" target="_blank" rel="noopener">Math Stack Exchange question</a>; here it is adapted for the blog with clearer exposition and code.</p>
<h2 id="the-problem">The Problem</h2>
<p>We want to solve the recurrence</p>
<p>$a_{n,m,k} = 2a_{n-1,m-1,k-1} + a_{n-1,m-1,k}$
$ + a_{n,m-1,k-1} + a_{n-1,m,k-1}$</p>
<p>where $m$, $n$, $k$ are nonnegative integers, with boundary conditions:</p>
<ul>
<li>$a_{0,0,0} = a_{0,1,0} = a_{1,0,0} = a_{0,0,1} = 1$</li>
<li>$a_{n,0,0} = a_{0,n,0} = a_{0,0,n} = 0$ for any $n &gt; 1$</li>
<li>$a_{n,m,k}$ is symmetric in $n$, $m$, $k$</li>
</ul>
<p>A subtlety: $a_{1,0,1}$ is not defined by the recurrence alone, since it would require values like $a_{0,-1,0}$. We take $a_{n,m,k} = 0$ whenever any subscript is negative.</p>
<h2 id="the-generating-function">The Generating Function</h2>
<p>Define</p>
<p>$$\Phi(x,y,z) = \sum_{n,m,k \geq 0} a_{n,m,k} \cdot x^n y^m z^k$$</p>
<p>Using the initial values above, we can write the recurrence including boundary terms as follows:</p>
<p>$a_{n,m,k} = 2a_{n-1,m-1,k-1} + a_{n-1,m-1,k}$
$ + a_{n,m-1,k-1} + a_{n-1,m,k-1}$
$ + [n=m=k=0] + [n=m=0 \wedge k=1]$
$ + [n=k=0 \wedge m=1] + [m=k=0 \wedge n=1]$</p>
<p>Substituting the recurrence into the generating function and collecting terms:</p>
<p>$\Phi(x,y,z) = \sum_{n,m,k} a_{n,m,k} \cdot x^n y^m z^k $
$ = 2\sum_{n,m,k} a_{n,m,k} \cdot x^{n+1} y^{m+1} z^{k+1} $
$ + \sum_{n,m,k} a_{n,m,k} \cdot x^{n+1} y^{m+1} z^k $
$ + \sum_{n,m,k} a_{n,m,k} \cdot x^{n+1} y^m z^{k+1} $
$ + \sum_{n,m,k} a_{n,m,k} \cdot x^n y^{m+1} z^{k+1} $
$ + 1 + x + y + z $
$ = 2 \Phi \cdot x y z + \Phi \cdot x y + \Phi \cdot x z + \Phi \cdot y z + 1 + x + y + z$
$ = \Phi \cdot ( 2 x y z + x y + x z + y z ) + 1 + x + y + z$</p>
<p>where the boundary terms $1 + x + y + z$ come from $a_{0,0,0}$, $a_{1,0,0}$, $a_{0,1,0}$, $a_{0,0,1}$.</p>
<p>Solving for $\Phi$:</p>
<p>$$\Phi(x,y,z) = \frac{1 + x + y + z}{1 - 2xyz - xy - xz - yz}$$</p>
<h2 id="from-generating-function-to-closed-form">From Generating Function to Closed Form</h2>
<p>Using</p>
<p>$$\frac{1}{1-\rho} = \sum_{i \geq 0} \rho^i$$</p>
<p>and the multinomial expansion</p>
<p>$$(x_1+x_2+x_3+x_4)^N = \sum_{r_1+r_2+r_3+r_4=N} \binom{N}{r_1,r_2,r_3,r_4} x_1^{r_1} x_2^{r_2} x_3^{r_3} x_4^{r_4}$$</p>
<p>with</p>
<p>$$\binom{N}{r_1,r_2,r_3,r_4} = \frac{N!}{r_1!\cdot r_2!\cdot r_3!\cdot r_4!}$$</p>
<p>we expand the denominator of $\Phi$. Let $\rho = 2xyz + xy + xz + yz$. Then</p>
<p>$$\Phi = \frac{1+x+y+z}{1-\rho} = (1+x+y+z) \sum_{N \geq 0} \rho^N$$</p>
<p>Expanding $\rho^N$ with the multinomial theorem (and writing $r_4 = N - r_1 - r_2 - r_3$):</p>
<p>$\sum_{N \geq 0} \rho^N = \sum_{N}(2 x y z + x y + x z + y z)^N $
$ = \sum_{r_1+r_2+r_3+r_4=N} \binom{N} {r_1,r_2,r_3,r_4} (2 x y z)^{r_1} \cdot (x y)^{r_2} \cdot (x z)^{r_3} \cdot (y z)^{r_4}$
$ = \sum_{r_1+r_2+r_3+r_4=N} \binom{N} {r_1,r_2,r_3,r_4} 2^{r_1} x^{r_1+r_2+r_3} y^{r_1+r_2+r_4} z^{r_1+r_3+r_4}$
$ = \sum_{r_1+r_2+r_3 \leq N} \binom{N} {r_1,r_2,r_3, N-r_1-r_2-r_3} 2^{r_1} x^{r_1+r_2+r_3} y^{N-r_3} z^{N-r_2}$</p>
<p>So we have</p>
<p>$$ \Phi = (1 + x + y + z) \sum_{r_1+r_2+r_3 \leq N} \binom{N} {r_1,r_2,r_3, N-r_1-r_2-r_3} 2^{r_1} x^{r_1+r_2+r_3} y^{N-r_3} z^{N-r_2}$$</p>
<p>Extracting the coefficient of $x^n y^m z^k$ gives the closed form. The full expression has four sums (from the numerator $1+x+y+z$):</p>
<p>$$a_{n,m,k} = \sum_{N=\max(n,m,k)}^{ (n+m+k)/2 } \binom{N}{n+m+k-2N, N-n, N-m, N-k} 2^{n+m+k-2N}$$
$$ + \sum_{N=\max(n,m-1,k)}^{ (n+m+k-1)/2 } \binom{N}{n+m+k-2N-1, N-n, N-m+1, N-k} 2^{n+m+k-2N-1}$$
$$ + \sum_{N=\max(n-1,m,k)}^{ (n+m+k-1)/2 } \binom{N}{n+m+k-2N-1, N-n+1, N-m, N-k} 2^{n+m+k-2N-1}$$
$$ + \sum_{N=\max(n,m,k-1)}^{ (n+m+k-1)/2 } \binom{N}{n+m+k-2N-1, N-n, N-m, N-k+1} 2^{n+m+k-2N-1}$$</p>
<p>There may be room to simplify this further; the symmetry in $n,m,k$ could help.</p>
<h2 id="complexity">Complexity</h2>
<p><strong>Recursion with memoization (DP):</strong></p>
<ul>
<li>time and space: $\Theta(n \cdot m \cdot k)$.</li>
</ul>
<p><strong>Closed form:</strong></p>
<ul>
<li>Precompute factorials, then loop over $N$;</li>
<li>time and space: $\Theta(n+m+k)$,</li>
<li>we ignore the cost of arithmetic on large integers.</li>
</ul>
<h2 id="implementation">Implementation</h2>
<p>Both the recursive and closed-form versions in Python:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-python" data-lang="python"><span style="display:flex;"><span><span style="color:#f92672">import</span> functools
</span></span><span style="display:flex;"><span><span style="color:#f92672">import</span> math
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-python" data-lang="python"><span style="display:flex;"><span><span style="color:#a6e22e">@functools.lru_cache</span>(maxsize<span style="color:#f92672">=</span><span style="color:#66d9ef">None</span>)
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">def</span> <span style="color:#a6e22e">a_rec</span>(n: int, m: int, k: int) <span style="color:#f92672">-&gt;</span> int:
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">if</span> <span style="color:#f92672">not</span> (n <span style="color:#f92672">&lt;=</span> m <span style="color:#f92672">&lt;=</span> k):
</span></span><span style="display:flex;"><span> n,m,k <span style="color:#f92672">=</span> sorted([n,m,k])
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">return</span> a_rec(n,m,k)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">if</span> n <span style="color:#f92672">&lt;</span> <span style="color:#ae81ff">0</span>:
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">return</span> <span style="color:#ae81ff">0</span>
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">if</span> n <span style="color:#f92672">+</span> m <span style="color:#f92672">+</span> k <span style="color:#f92672">&lt;=</span> <span style="color:#ae81ff">1</span>:
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">return</span> <span style="color:#ae81ff">1</span>
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">if</span> n <span style="color:#f92672">+</span> m <span style="color:#f92672">==</span> <span style="color:#ae81ff">0</span> <span style="color:#f92672">or</span> n <span style="color:#f92672">+</span> k <span style="color:#f92672">==</span> <span style="color:#ae81ff">0</span> <span style="color:#f92672">or</span> m <span style="color:#f92672">+</span> k <span style="color:#f92672">==</span> <span style="color:#ae81ff">0</span>:
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">return</span> <span style="color:#ae81ff">0</span>
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">if</span> n <span style="color:#f92672">==</span> <span style="color:#ae81ff">0</span>:
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">return</span> int(m <span style="color:#f92672">+</span> <span style="color:#ae81ff">1</span> <span style="color:#f92672">&gt;=</span> k)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">return</span> (
</span></span><span style="display:flex;"><span> <span style="color:#ae81ff">2</span> <span style="color:#f92672">*</span> a_rec(n <span style="color:#f92672">-</span> <span style="color:#ae81ff">1</span>, m <span style="color:#f92672">-</span> <span style="color:#ae81ff">1</span>, k <span style="color:#f92672">-</span> <span style="color:#ae81ff">1</span>)
</span></span><span style="display:flex;"><span> <span style="color:#f92672">+</span> a_rec(n <span style="color:#f92672">-</span> <span style="color:#ae81ff">1</span>, m <span style="color:#f92672">-</span> <span style="color:#ae81ff">1</span>, k)
</span></span><span style="display:flex;"><span> <span style="color:#f92672">+</span> a_rec(n <span style="color:#f92672">-</span> <span style="color:#ae81ff">1</span>, m, k <span style="color:#f92672">-</span> <span style="color:#ae81ff">1</span>)
</span></span><span style="display:flex;"><span> <span style="color:#f92672">+</span> a_rec(n, m <span style="color:#f92672">-</span> <span style="color:#ae81ff">1</span>, k <span style="color:#f92672">-</span> <span style="color:#ae81ff">1</span>)
</span></span><span style="display:flex;"><span> )
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-python" data-lang="python"><span style="display:flex;"><span><span style="color:#a6e22e">@functools.lru_cache</span>(maxsize<span style="color:#f92672">=</span><span style="color:#66d9ef">None</span>)
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">def</span> <span style="color:#a6e22e">binom4</span>(N: int, r1: int, r2: int, r3: int) <span style="color:#f92672">-&gt;</span> int:
</span></span><span style="display:flex;"><span> r4 <span style="color:#f92672">=</span> N <span style="color:#f92672">-</span> r1 <span style="color:#f92672">-</span> r2 <span style="color:#f92672">-</span> r3
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">return</span> math<span style="color:#f92672">.</span>factorial(N) <span style="color:#f92672">//</span> (
</span></span><span style="display:flex;"><span> math<span style="color:#f92672">.</span>factorial(r1) <span style="color:#f92672">*</span> math<span style="color:#f92672">.</span>factorial(r2)
</span></span><span style="display:flex;"><span> <span style="color:#f92672">*</span> math<span style="color:#f92672">.</span>factorial(r3) <span style="color:#f92672">*</span> math<span style="color:#f92672">.</span>factorial(r4)
</span></span><span style="display:flex;"><span> )
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">def</span> <span style="color:#a6e22e">a_closed</span>(n: int, m: int, k: int) <span style="color:#f92672">-&gt;</span> int:
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">if</span> min(n, m, k) <span style="color:#f92672">&lt;</span> <span style="color:#ae81ff">0</span>:
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">return</span> <span style="color:#ae81ff">0</span>
</span></span><span style="display:flex;"><span> s <span style="color:#f92672">=</span> <span style="color:#ae81ff">0</span>
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">for</span> N <span style="color:#f92672">in</span> range(max(n, m, k), (n <span style="color:#f92672">+</span> m <span style="color:#f92672">+</span> k) <span style="color:#f92672">//</span> <span style="color:#ae81ff">2</span> <span style="color:#f92672">+</span> <span style="color:#ae81ff">1</span>):
</span></span><span style="display:flex;"><span> s <span style="color:#f92672">+=</span> binom4(N, N <span style="color:#f92672">-</span> n, N <span style="color:#f92672">-</span> m, N <span style="color:#f92672">-</span> k) <span style="color:#f92672">*</span> <span style="color:#ae81ff">2</span> <span style="color:#f92672">**</span> (n <span style="color:#f92672">+</span> m <span style="color:#f92672">+</span> k <span style="color:#f92672">-</span> <span style="color:#ae81ff">2</span> <span style="color:#f92672">*</span> N)
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">for</span> N <span style="color:#f92672">in</span> range(max(n, m <span style="color:#f92672">-</span> <span style="color:#ae81ff">1</span>, k), (n <span style="color:#f92672">+</span> m <span style="color:#f92672">+</span> k <span style="color:#f92672">-</span> <span style="color:#ae81ff">1</span>) <span style="color:#f92672">//</span> <span style="color:#ae81ff">2</span> <span style="color:#f92672">+</span> <span style="color:#ae81ff">1</span>):
</span></span><span style="display:flex;"><span> s <span style="color:#f92672">+=</span> binom4(N, N <span style="color:#f92672">-</span> n, N <span style="color:#f92672">-</span> m <span style="color:#f92672">+</span> <span style="color:#ae81ff">1</span>, N <span style="color:#f92672">-</span> k) <span style="color:#f92672">*</span> <span style="color:#ae81ff">2</span> <span style="color:#f92672">**</span> (n <span style="color:#f92672">+</span> m <span style="color:#f92672">+</span> k <span style="color:#f92672">-</span> <span style="color:#ae81ff">2</span> <span style="color:#f92672">*</span> N <span style="color:#f92672">-</span> <span style="color:#ae81ff">1</span>)
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">for</span> N <span style="color:#f92672">in</span> range(max(n <span style="color:#f92672">-</span> <span style="color:#ae81ff">1</span>, m, k), (n <span style="color:#f92672">+</span> m <span style="color:#f92672">+</span> k <span style="color:#f92672">-</span> <span style="color:#ae81ff">1</span>) <span style="color:#f92672">//</span> <span style="color:#ae81ff">2</span> <span style="color:#f92672">+</span> <span style="color:#ae81ff">1</span>):
</span></span><span style="display:flex;"><span> s <span style="color:#f92672">+=</span> binom4(N, N <span style="color:#f92672">-</span> n <span style="color:#f92672">+</span> <span style="color:#ae81ff">1</span>, N <span style="color:#f92672">-</span> m, N <span style="color:#f92672">-</span> k) <span style="color:#f92672">*</span> <span style="color:#ae81ff">2</span> <span style="color:#f92672">**</span> (n <span style="color:#f92672">+</span> m <span style="color:#f92672">+</span> k <span style="color:#f92672">-</span> <span style="color:#ae81ff">2</span> <span style="color:#f92672">*</span> N <span style="color:#f92672">-</span> <span style="color:#ae81ff">1</span>)
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">for</span> N <span style="color:#f92672">in</span> range(max(n, m, k <span style="color:#f92672">-</span> <span style="color:#ae81ff">1</span>), (n <span style="color:#f92672">+</span> m <span style="color:#f92672">+</span> k <span style="color:#f92672">-</span> <span style="color:#ae81ff">1</span>) <span style="color:#f92672">//</span> <span style="color:#ae81ff">2</span> <span style="color:#f92672">+</span> <span style="color:#ae81ff">1</span>):
</span></span><span style="display:flex;"><span> s <span style="color:#f92672">+=</span> binom4(N, N <span style="color:#f92672">-</span> n, N <span style="color:#f92672">-</span> m, N <span style="color:#f92672">-</span> k <span style="color:#f92672">+</span> <span style="color:#ae81ff">1</span>) <span style="color:#f92672">*</span> <span style="color:#ae81ff">2</span> <span style="color:#f92672">**</span> (n <span style="color:#f92672">+</span> m <span style="color:#f92672">+</span> k <span style="color:#f92672">-</span> <span style="color:#ae81ff">2</span> <span style="color:#f92672">*</span> N <span style="color:#f92672">-</span> <span style="color:#ae81ff">1</span>)
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">return</span> s
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-python" data-lang="python"><span style="display:flex;"><span><span style="color:#f92672">import</span> timeit
</span></span><span style="display:flex;"><span>setup_code <span style="color:#f92672">=</span> <span style="color:#e6db74">&#34;from __main__ import a_rec, a_closed&#34;</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>execution_time <span style="color:#f92672">=</span> timeit<span style="color:#f92672">.</span>timeit(<span style="color:#e6db74">&#39;a_rec(200, 300, 400)&#39;</span>, setup<span style="color:#f92672">=</span>setup_code, number<span style="color:#f92672">=</span><span style="color:#ae81ff">1</span>)
</span></span><span style="display:flex;"><span>print(<span style="color:#e6db74">f</span><span style="color:#e6db74">&#34;Execution time for recursive: </span><span style="color:#e6db74">{</span>execution_time<span style="color:#e6db74">}</span><span style="color:#e6db74"> seconds&#34;</span>)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>execution_time <span style="color:#f92672">=</span> timeit<span style="color:#f92672">.</span>timeit(<span style="color:#e6db74">&#39;a_closed(200, 300, 400)&#39;</span>, setup<span style="color:#f92672">=</span>setup_code, number<span style="color:#f92672">=</span><span style="color:#ae81ff">1</span>)
</span></span><span style="display:flex;"><span>print(<span style="color:#e6db74">f</span><span style="color:#e6db74">&#34;Execution time for closed form: </span><span style="color:#e6db74">{</span>execution_time<span style="color:#e6db74">}</span><span style="color:#e6db74"> seconds&#34;</span>)
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-text" data-lang="text"><span style="display:flex;"><span>Execution time for recursive: 8.308788761030883 seconds
</span></span><span style="display:flex;"><span>Execution time for closed form: 0.003819321980699897 seconds
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-python" data-lang="python"><span style="display:flex;"><span><span style="color:#75715e"># Sanity check</span>
</span></span><span style="display:flex;"><span>res0 <span style="color:#f92672">=</span> a_rec(<span style="color:#ae81ff">100</span>, <span style="color:#ae81ff">200</span>, <span style="color:#ae81ff">210</span>)
</span></span><span style="display:flex;"><span>res1 <span style="color:#f92672">=</span> a_closed(<span style="color:#ae81ff">100</span>, <span style="color:#ae81ff">200</span>, <span style="color:#ae81ff">210</span>)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>print(<span style="color:#e6db74">f</span><span style="color:#e6db74">&#34;Recursive: </span><span style="color:#e6db74">{</span>res0<span style="color:#e6db74">}</span><span style="color:#e6db74">&#34;</span>)
</span></span><span style="display:flex;"><span>print(<span style="color:#e6db74">f</span><span style="color:#e6db74">&#34;Closed: </span><span style="color:#e6db74">{</span>res1<span style="color:#e6db74">}</span><span style="color:#e6db74">&#34;</span>)
</span></span><span style="display:flex;"><span>print(<span style="color:#e6db74">f</span><span style="color:#e6db74">&#34;Match: </span><span style="color:#e6db74">{</span>res0 <span style="color:#f92672">==</span> res1<span style="color:#e6db74">}</span><span style="color:#e6db74">&#34;</span>)
</span></span></code></pre></div><p>We did not exploit the symmetry $a_{n,m,k} = a_{\sigma(n,m,k)}$ for permutations $\sigma$; it could speed up computation but does not obviously simplify the closed expression.</p>
<hr>
<p><em>Originally answered on <a href="https://math.stackexchange.com/questions/1093271/how-to-solve-this-multivariable-recursion/2730331#2730331" target="_blank" rel="noopener">Math Stack Exchange</a>.</em></p>
</description>
</item>
<item>
<title>Multiplicative Hashing Functions -- Notes on Primes, Golden Ratio, and Evil</title>
<link>/post/multiplicative-hash/</link>
<pubDate>Wed, 02 Aug 2017 07:29:43 +0000</pubDate>
<guid>/post/multiplicative-hash/</guid>
<description><h2 id="introduction">Introduction</h2>
<p>Mapping partitions (or keys) to slices (or buckets) in a distributed or sharded system has a large impact on performance.
Different hash-based solutions for this problem exist; each has drawbacks.
The goal is to choose a hash function that is simple to implement and gives acceptable performance with as few collisions as possible.</p>
<p>The problem is defined as follows. Given a logical partition number $P$, compute the corresponding slice number $S = s(P)$.
Where $0 ≤ P &lt; 2^{32}$, $0 ≤ S &lt; M$, and $M$ denotes the table size (e.g. $M = 2^{14}$).
In our &ldquo;binary&rdquo; world, assumptions that input data (partition numbers) have uniform distribution are not always correct.
Therefore, the hash function $s: P \to S$ must be designed very carefully.
In addition to providing uniform distribution of hash values (slice numbers), it has to add some randomness.
Luckily, this field is well studied: well-known textbooks of Corman&rsquo;s and Knuth&rsquo;s have a good introduction to this field.
The last one has more detail explanation; therefore, without hesitation, we make use of Knuth&rsquo;s book (Section 6.4.):
usually explaining in two paragraphs what the book is saying just in one sentence.</p>
<h2 id="basic-ideas">Basic Ideas</h2>
<p>A first approach is the division-remainder method with $M$ a power of 2:</p>
<p>$s(P) = P \bmod M$,</p>
<p>where $M = 2^{14}$ is the table size (number of slices). A variant is to take $M$ prime instead:</p>
<p>$s(P) = P \bmod M$,</p>
<p>where $M = 16411$ is a prime $&gt; 2^{14}$. Both forms are called &ldquo;Division Remainder Method&rdquo;. These notes focus on another method, the &ldquo;Multiplicative Method&rdquo;:</p>
<p>$$f(P) = A \cdot P \bmod W$$</p>
<p>$$s(P) = f(P) \div (W \div M)$$</p>
<p>Where $W = 2^{32}$ &ndash; the machine word, $M = 2^{14}$ &ndash; the table size, $\div$ denotes an integer division, $W \div M = 2^{32 - 14} = 2^{18}$, $A = 2654435761$ &ndash; some &ldquo;magic&rdquo; integer.
It will be explained later, for now we assume that due to this magic, the value of $f(P)$ is almost random.
It is easy to see that $s(P)$ is in valid interval of slices, between 0 and $M = 2^{14}$.</p>
<h3 id="example-of-hash-codes">Example of Hash Codes</h3>
<table>
<thead>
<tr>
<th>partition $P$</th>
<th>dec $P$</th>
<th>hex $P$</th>
<th>binary $f(P)$</th>
<th>binary $S$</th>
<th>hex $S$</th>
<th>dec $S$</th>
</tr>
</thead>
<tbody>
<tr>
<td>$0$</td>
<td>0</td>
<td>00000000</td>
<td>00000000000000000000000000000000</td>
<td>00000000000000</td>
<td>0000</td>
<td>0</td>
</tr>
<tr>
<td>$1$</td>
<td>1</td>
<td>00000001</td>
<td>10011110001101110111100110110001</td>
<td>10011110001101</td>
<td>278D</td>
<td>10125</td>
</tr>
<tr>
<td>$2$</td>
<td>2</td>
<td>00000002</td>
<td>00111100011011101111001101100010</td>
<td>00111100011011</td>
<td>0F1B</td>
<td>3867</td>
</tr>
<tr>
<td>$3$</td>
<td>3</td>
<td>00000003</td>
<td>11011010101001100110110100010011</td>
<td>11011010101001</td>
<td>36A9</td>
<td>13993</td>
</tr>
<tr>
<td>$2^{14}-1$</td>
<td>16383</td>
<td>00003FFF</td>
<td>01000000001101001100011001001111</td>
<td>01000000001101</td>
<td>100D</td>
<td>4109</td>
</tr>
<tr>
<td>$2^{14}$</td>
<td>16384</td>
<td>00004000</td>
<td>11011110011011000100000000000000</td>
<td>11011110011011</td>
<td>379B</td>
<td>14235</td>
</tr>
<tr>
<td>$2^{14}+1$</td>
<td>16385</td>
<td>00004001</td>
<td>01111100101000111011100110110001</td>
<td>01111100101000</td>
<td>1F28</td>
<td>7976</td>
</tr>
<tr>
<td>$2^{14}+2$</td>
<td>16386</td>
<td>00004002</td>
<td>00011010110110110011001101100010</td>
<td>00011010110110</td>
<td>06B6</td>
<td>1718</td>
</tr>
<tr>
<td>$2^{15}-1$</td>
<td>32767</td>
<td>00007FFF</td>
<td>00011110101000010000011001001111</td>
<td>00011110101000</td>
<td>07A8</td>
<td>1960</td>
</tr>
<tr>
<td>$2^{15}$</td>
<td>32768</td>
<td>00008000</td>
<td>10111100110110001000000000000000</td>
<td>10111100110110</td>
<td>2F36</td>
<td>12086</td>
</tr>
<tr>
<td>$2^{15}+1$</td>
<td>32769</td>
<td>00008001</td>
<td>01011011000011111111100110110001</td>
<td>01011011000011</td>
<td>16C3</td>
<td>5827</td>
</tr>
<tr>
<td>$2^{15}+2$</td>
<td>32770</td>
<td>00008002</td>
<td>11111001010001110111001101100010</td>
<td>11111001010001</td>
<td>3E51</td>
<td>15953</td>
</tr>
<tr>
<td>$2^{30}-1$</td>
<td>1073741823</td>
<td>3FFFFFFF</td>
<td>10100001110010001000011001001111</td>
<td>10100001110010</td>
<td>2872</td>
<td>10354</td>
</tr>
<tr>
<td>$2^{30}$</td>
<td>1073741824</td>
<td>40000000</td>
<td>01000000000000000000000000000000</td>
<td>01000000000000</td>
<td>1000</td>
<td>4096</td>
</tr>
<tr>
<td>$2^{30}+1$</td>
<td>1073741825</td>
<td>40000001</td>
<td>11011110001101110111100110110001</td>
<td>11011110001101</td>
<td>378D</td>
<td>14221</td>
</tr>
<tr>
<td>$2^{30}+2$</td>
<td>1073741826</td>
<td>40000002</td>
<td>01111100011011101111001101100010</td>
<td>01111100011011</td>
<td>1F1B</td>
<td>7963</td>
</tr>
<tr>
<td>$2^{31}-1$</td>
<td>2147483647</td>
<td>7FFFFFFF</td>
<td>11100001110010001000011001001111</td>
<td>11100001110010</td>
<td>3872</td>
<td>14450</td>
</tr>
<tr>
<td>$2^{31}$</td>
<td>2147483648</td>
<td>80000000</td>
<td>10000000000000000000000000000000</td>
<td>10000000000000</td>
<td>2000</td>
<td>8192</td>
</tr>
<tr>
<td>$2^{31}+1$</td>
<td>2147483649</td>
<td>80000001</td>
<td>00011110001101110111100110110001</td>
<td>00011110001101</td>
<td>078D</td>
<td>1933</td>
</tr>
<tr>
<td>$2^{31}+2$</td>
<td>2147483650</td>
<td>80000002</td>
<td>10111100011011101111001101100010</td>
<td>10111100011011</td>
<td>2F1B</td>
<td>12059</td>
</tr>
<tr>
<td>$2^{32}-1$</td>
<td>4294967295</td>
<td>FFFFFFFF</td>
<td>01100001110010001000011001001111</td>
<td>01100001110010</td>
<td>1872</td>
<td>6258</td>
</tr>
</tbody>
</table>
<h3 id="implementation-in-c">Implementation in C</h3>
<p>The new hashing function looks at bit complicated, so let&rsquo;s consider how it (and others) could be implemented in C code. The type uint32_t denotes 32-bit unsigned integer. We start from examples of Division Remainder hashing. For $M$ being a power of 2:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-c" data-lang="c"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#66d9ef">uint32_t</span> M <span style="color:#f92672">=</span> <span style="color:#ae81ff">2</span> <span style="color:#f92672">&lt;&lt;</span> <span style="color:#ae81ff">14</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">uint32_t</span> <span style="color:#a6e22e">slice</span>(<span style="color:#66d9ef">uint32_t</span> P) {
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">return</span> P <span style="color:#f92672">&amp;</span> (M <span style="color:#f92672">-</span> <span style="color:#ae81ff">1</span>);
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>For prime $M$:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-c" data-lang="c"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#66d9ef">uint32_t</span> M <span style="color:#f92672">=</span> <span style="color:#ae81ff">16411</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">uint32_t</span> <span style="color:#a6e22e">slice</span>(<span style="color:#66d9ef">uint32_t</span> P) {
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">return</span> P <span style="color:#f92672">%</span> M;
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>The next function implements Multiplicative hashing:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-c" data-lang="c"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#66d9ef">uint32_t</span> M <span style="color:#f92672">=</span> <span style="color:#ae81ff">2</span> <span style="color:#f92672">&lt;&lt;</span> <span style="color:#ae81ff">14</span>;
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#66d9ef">uint32_t</span> A <span style="color:#f92672">=</span> <span style="color:#ae81ff">2654435761</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">uint32_t</span> <span style="color:#a6e22e">slice</span>(<span style="color:#66d9ef">uint32_t</span> P) {
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">return</span> (P <span style="color:#f92672">*</span> A) <span style="color:#f92672">&gt;&gt;</span> <span style="color:#ae81ff">18</span>;
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>It works well for arbitrary input data and allows using the same number of slices $M = 2^{14}$. As the reader can see, the multiplicative version uses only a multiplication and a logical shift; on some architectures it can be faster than computing a modulo.</p>
<p>Details for Math Fans</p>
<p>In this section we describe properties of every approach. On analysis of the simple functions, we demonstrate the informal tools that we later apply to more complex functions. We hope that even non great fan of mathematics will be able to catch the main point.</p>
<h2 id="the-power-of-2-is-evil">The Power of 2 is Evil</h2>
<p>The first function we will consider is $s(P) = P \bmod 2^{14}$.
Let&rsquo;s recall some properties of this function.</p>
<p>Flipping just one bit in the given partition not always leads to a change in the corresponding slice (in hash-value).
More formal: for some bit $i$, &ldquo;occasionally&rdquo; $s(P) = s(P + 2^i)$ holds; here we assume for simplicity that $P$ has $i$ bit cleared.
In our &ldquo;binary&rdquo; world, partitions differing in only one bit may have a strong correlation.
Therefore, we are expecting that a &ldquo;good&rdquo; hashing will produce different hash-code for them (i.e., it will place the partitions in different slices).
But for this function, the property fails on any partition $P ≥ 2^{14}$.
There are simple templates of partitions having the same hash-code.
For example, for any $i$ and $S$, partitions $P = S + 2^{14} \cdot i$ will be placed by the function to the same slice $S$.
From a &ldquo;good&rdquo; hashing, we are expecting not to have very common patterns, especially, of binary form.
But again, this function fails on this condition.</p>
<h2 id="the-art-of-primes">The Art of Primes</h2>
<p>The second function is $s(P) = P \bmod M$.
Where $M = 16411$.
For this function, flipping any bit in a partition $P$ changes the hash code, because $M$ is chosen to be a prime.
Actually, this condition on $M$ is too strong.
For satisfying this property, it is sufficient that $M ≠ 2^i$ will hold.
For example, $M = 15 · 12 · 97 = 17460$ (15 modules, 12 disks, 97 is a prime) is also &ldquo;good&rdquo;.</p>
<p>Since $M$ is prime, it seems that the following pattern is not common: $P = S + M · i$. But actually, primes that are close to a power of 2 are also not good. Knuth recommends to choose such $M$ that the following condition will not hold for any small integers $a$ and $j$: $r^j ≡ ± a \pmod M$. Where $r$ denotes the base of computation. From explanation of Knuth, the meaning of $r$ for our case is not too clear: whether $r=2$, $r=16$, or $r=256$? It seems the answer very depends on the type of input data.</p>
<p>By Knuth, if $r=2$, the chosen $M$ is not so good, since $M = 16411 = 2^{14} + 27$, and hence $2^{14} ≡ -27 \pmod M$. For $r=16$, we get that $16^4 ≡ -108 \pmod M$. For $r=256$, $256^2 ≡ -108 \pmod M$.</p>
<p>Knuth explains that such $M$ may produce a hash code that is a simple composition of key digits (in $r$ base system). Instead of trying to understand this explanation, we will give some intuition. Working with numbers, a programmer usually chooses powers of 2 for sizes of structures and buffers (e.g., $2^{10}$ bytes). Then he defines the format of such data and introduces headers (e.g. the header size = 20 bytes). Hence, the size of data without the header becomes very close to the power of 2 (in our example, $2^{10} - 20 = 1004$). On the other hand, embedding this structure to an outer packet (assume the size of this outer header is 30 bytes) leads to the total size being also close to the power of 2 ($2^{10} + 30 = 1054$). As result, most of numbers in our &ldquo;binary&rdquo; world are either powers of 2 or close to them. Therefore, such choice of $M$ increases collisions. In other words, not only powers of 2 are <em>evil</em>, but primes closing to them are <em>evil</em> too.</p>
<p>As an example of a &ldquo;good&rdquo; prime, let&rsquo;s consider $M = 24571$. It is a bit smaller then the middle of $2^{14}$ and $2^{15}$.</p>
<p>Introducing a little change in this hashing function, we get better hashing even for $M = 2^{14}$: $s(P) = P \bmod N \bmod M$. In this case $N$ must be some &ldquo;big&rdquo; and &ldquo;far&rdquo; from a power of 2 prime number. The discussion of this method is out of scope of this Notes.</p>
<h2 id="the-magic-of-golden-ratio">The Magic of Golden Ratio</h2>
<p>We now present in details the multiplicative hashing. First, we discuss the properties of the function $f$: $f(P) = A · P \bmod W$.</p>
<p>The magic number $A$ is chosen to have the following nice properties: $W / A ≈ 1.6$ &ndash; the golden ratio and $GCD(A, W) = 1$ ($A$ and $W$ are relatively prime or coprime). Therefore, the function $f$ is 1-1 on 32-bit integers. In other word, for any $P_1~ ≠ P_2$, $f(P_1) ≠ f(P_2)$ holds. This function has a role of perturbation or randomization of the input data (partitions).</p>
<p>Assume given a partition $P$. Let&rsquo;s set the 0 bit in $P$. Then we get $f(P + 1) = (f(P) + A) \bmod W$. So the bit 0 dirties those bits of $f(P)$ that are set in $A$. This implies that $A$ must be chosen from the following range: $2^{31} &lt; A &lt; 2^{32}$, and in addition it must have a half of bits being set. By Knuth, the best choice is to define it to be the golden value of $W$: $W / A = 1.6 \ldots$ . In this case setting $i$-bit in $P$ dirties in $f(P)$ all the bits from $i$ to 31.</p>
<p>Using the properties of $f()$, we show the intuition why the function $s(P) = f(P) \div 2^{18}$ is a &ldquo;good&rdquo; hashing function.</p>
<p>The function $s$ remains 14 most significant bits of $f(P)$. Therefore, from the properties of $f()$, flipping any bit in $P$ will yield flipping at least in one bit of $s(P)$.
The function $s$ puts into one slice $S$ all the partitions of the form: $P = (S · 2^{18} + i) · B \bmod 2^{32}$, where $B = 244002641$ (see for details the section Invertibility) and $0 ≤ i &lt; 2^{18}$. Assume that $P_0 = S · B · 2^{18} \bmod 2^{32}$, then $P_i = (P_0 + i · B) \bmod 2^{32}$. The function $g(i) = i · B$ produces almost random 32-bit integers from 18-bit integers. Therefore, it is almost impossible to derive a &ldquo;nice&rdquo; sub-sequence from the values of set ${g(i) | 0 ≤ i &lt; 2^{18}}$.</p>
<h2 id="invertibility">Invertibility</h2>
<p>Given a 14-bit slice $S$ and some 18-bit identifier $Id$, we are interested to compute the partition $P$ that is placed by the function $s$ at slice $S$. Note that given a partition $P$, the computation of $Id$ is also depends on the chosen method of hashing. We present for each hashing how the identifier and the inverse of $s()$ can be computed.</p>
<p>For the simplest function $s(P) = P \bmod 2^{14}$, the identifier is computed as follows: $Id = P \div 2^{14}$.
Then its inverse is $p(S, Id) = S + Id · 2^{14}$.
For prime $M$, the identifier is $Id = P \div M$ and the inverse function is $p(S, Id) = S + Id · M$.
For multiplicative hashing, we have $Id = A · P \bmod 2^{14}$. Then $p(S, Id) = (S · 2^{18} + Id) · B \bmod 2^{32}$.
This implies from the fact that $A · B ≡ 1 \pmod 2^{32}$ and the inverse of $f()$ is $f^{-1}(x) = x · B \bmod 2^{32}$.</p>
<p>We show the implementation of $p()$ in C code for the multiplicative hashing only:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-c" data-lang="c"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#66d9ef">uint32_t</span> M <span style="color:#f92672">=</span> <span style="color:#ae81ff">2</span> <span style="color:#f92672">&lt;&lt;</span> <span style="color:#ae81ff">14</span>;
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#66d9ef">uint32_t</span> B <span style="color:#f92672">=</span> <span style="color:#ae81ff">244002641</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">uint32_t</span> <span style="color:#a6e22e">partition</span>(<span style="color:#66d9ef">uint32_t</span> S, <span style="color:#66d9ef">uint32_t</span> Id) {
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">return</span> (S <span style="color:#f92672">&lt;&lt;</span> <span style="color:#ae81ff">18</span> <span style="color:#f92672">+</span> Id) <span style="color:#f92672">*</span> B;
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><h2 id="big-numbers">Big Numbers</h2>
<p>In this section we discuss the behavior of multiplicative hashing on big partition numbers. Recall that flipping just one $i$-bit in $P$ has impact on $(32 - i)$ bits (from $i$ to 31) in $f(P)$. By the definition, $s(P)$ derives 14 most significant bits of $f(P)$. As result, for $i &lt; 18$, the flipping $i$-bit dirties most of 14 bits of $s(P)$, while for $i ≥ 18$, it change less then 14 bits of $s(P)$: $32 - i ≤ 14$. For example, flipping the most significant 31-bit of the partition $P$ flips the only one 14-bit of the corresponding slice $S = s(P)$. This is not a real problem for our case, the partitions are still putted into different slides.</p>
<p>Another problem with flipping of most significant bits is following. For a set of partitions differing in most significant bits only, the number of collisions is greater then for the case that partitions are different in less significant bits. But due to the nice choice of $A$ (being golden ratio of $W$), this is still sufficiently good distribution. Intuitively, if the partitions differ in x most significant bits, then slices for them will also differ in x bits. So most of these partitions will be placed to different slices.</p>
<p>Note that the number of impacted bits in $s(P)$ decreases only for partitions with more then 18 bits. Even then, as described above, it does not mean that we will have a huge degradation of the hashing performance. But if we want to prevent any potentially dangerous case, we may extend the machine word to 64-bits, especially if the used architecture is also 64-bit. In this case, we just compute a new pair of integers $A$ and $B$ ($A$ is the golden ration of and is coprime with $W=2^{64}$, $B$ is coprime with $A$) and correct logical shifts. This is an example of implementation in C:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-c" data-lang="c"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#66d9ef">uint64_t</span> M <span style="color:#f92672">=</span> <span style="color:#ae81ff">2</span> <span style="color:#f92672">&lt;&lt;</span> <span style="color:#ae81ff">14</span>;
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#66d9ef">uint64_t</span> A <span style="color:#f92672">=</span> <span style="color:#ae81ff">11400714819323198485</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">uint64_t</span> <span style="color:#a6e22e">slice</span>(<span style="color:#66d9ef">uint64_t</span> P) {
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">return</span> (P <span style="color:#f92672">*</span> A) <span style="color:#f92672">&gt;&gt;</span> <span style="color:#ae81ff">50</span>;
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><h3 id="example-of-big-partitions">Example of Big Partitions</h3>
<p>The table contains computation of slices for partitions that differ only in three most significant bits. As we can see, corresponding slices also differ only in three bits. This property may be considered as drawback. But note that this case has no collisions.</p>
<table>
<thead>
<tr>
<th>binary $P$</th>
<th>hex $P$</th>
<th>binary $f(P)$</th>
<th>binary $S$</th>
<th>hex $S$</th>
<th>dec $S$</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>000</strong>10101010111010100100101011001</td>
<td>155D4959</td>
<td><strong>100</strong>01101010010011100011110001001</td>
<td><strong>100</strong>01101010010</td>
<td>$2352$</td>
<td>$9042$</td>
</tr>
<tr>
<td><strong>001</strong>10101010111010100100101011001</td>
<td>355D4959</td>
<td><strong>101</strong>01101010010011100011110001001</td>
<td><strong>101</strong>01101010010</td>
<td>$2B52$</td>
<td>$11090$</td>
</tr>
<tr>
<td><strong>010</strong>10101010111010100100101011001</td>
<td>555D4959</td>
<td><strong>110</strong>01101010010011100011110001001</td>
<td><strong>110</strong>01101010010</td>
<td>$3352$</td>
<td>$13138$</td>
</tr>
<tr>
<td><strong>011</strong>10101010111010100100101011001</td>
<td>755D4959</td>
<td><strong>111</strong>01101010010011100011110001001</td>
<td><strong>111</strong>01101010010</td>
<td>$3B52$</td>
<td>$15186$</td>
</tr>
<tr>
<td><strong>100</strong>10101010111010100100101011001</td>
<td>955D4959</td>
<td><strong>000</strong>01101010010011100011110001001</td>
<td><strong>000</strong>01101010010</td>
<td>$0352$</td>
<td>$850$</td>
</tr>
<tr>
<td><strong>101</strong>10101010111010100100101011001</td>
<td>B55D4959</td>
<td><strong>001</strong>01101010010011100011110001001</td>
<td><strong>001</strong>01101010010</td>
<td>$0B52$</td>
<td>$2898$</td>
</tr>
<tr>
<td><strong>110</strong>10101010111010100100101011001</td>
<td>D55D4959</td>
<td><strong>010</strong>01101010010011100011110001001</td>
<td><strong>010</strong>01101010010</td>
<td>$1352$</td>
<td>$4946$</td>
</tr>
<tr>
<td><strong>111</strong>10101010111010100100101011001</td>
<td>F55D4959</td>
<td><strong>011</strong>01101010010011100011110001001</td>
<td><strong>011</strong>01101010010</td>
<td>$1B52$</td>
<td>$6994$</td>
</tr>
</tbody>
</table>
<h2 id="conclusion">Conclusion</h2>
<p>TODO</p>
<h3 id="links-and-references">Links and References</h3>
<ul>
<li>T Corman, Ch Leiserson, R Rivest, &ldquo;Introduction to Algorithms&rdquo;, 1999</li>
<li>D Knuth, &ldquo;Sorting and Searching&rdquo;, volume 3 of &ldquo;The Art of Computer Programming&rdquo;, 1973. Section 12.3</li>
<li>Integer Hash Function, Thomas Wang</li>
<li>Selecting a Hash Function, Scott Gasch</li>
<li>Hash functions, Paul Hsieh</li>
<li>Wikipedia: Hash Table &ndash; sites Thomas Wang that the multiplicative hash has &ldquo;particularly poor clustering behavior&rdquo;.</li>
<li>Prime Double Hash Table, Thomas Wang &ndash; the wrong proof.</li>
<li><a href="http://web.archive.org/web/19990903133921/http://www.concentric.net/~Ttwang/tech/primehash.htm" target="_blank" rel="noopener">http://web.archive.org/web/19990903133921/http://www.concentric.net/~Ttwang/tech/primehash.htm</a></li>
<li>Wikipedia: Talking Hash Table &ndash; note that the proof is wrong, see &ldquo;Info about multiplicative hashing is wrong&rdquo; section.</li>
</ul>
</description>
</item>
<item>
<title>Perfect Distribution: GCD in Disguise</title>
<link>/post/perfect-distribution/</link>
<pubDate>Tue, 01 Aug 2017 07:29:43 +0000</pubDate>
<guid>/post/perfect-distribution/</guid>
<description><h2 id="perfect-distribution-gcd-in-disguise">Perfect Distribution: GCD in Disguise</h2>
<p>We discuss an algorithm that distributes $a$ ones among $n$ positions so that the gaps between consecutive ones differ by at most one—a <strong>perfect distribution</strong>. I developed it while working on profiling, stress, and negative testing of a system that needed exactly this kind of uniform spread. I am not aware of prior art; if you know of related work, I would be interested to hear.</p>
<p>The examples below are software engineering use cases for this algorithm.</p>
<h3 id="use-case-0-text-spacing">Use Case 0: Text spacing</h3>
<p>Given a string of characters $s$ and a number $n$ greater than the length of $s$,
extend the string $s$ to length $n$ by inserting spaces between the words.
The key requirement is that the distances between two consecutive words be uniform.</p>
<h3 id="use-case-1-stress-testing">Use Case 1: Stress testing</h3>
<p>Assume we want to stress-test a server.
Our test contains positive and negative requests.
Suppose we want to send $1000$ requests, $300$ of which are negative.
Our test tool might send requests simultaneously or sequentially,
but we require that the negative requests arrive at the server with uniform distribution.
I.e., we want to avoid sending 300 negative followed by 700 positive requests.
Using the algorithm, we simply distribute the 300 negative requests by calling ${\cal PD}(300, 1000)$:
cell $i$ is $1$ if and only if request $i$ is negative.
The test tool then uses the array to send requests (possibly sequentially).</p>
<h3 id="use-case-2-rate-limiting--profiling">Use Case 2: Rate limiting / profiling</h3>
<p>Assume the test tool can run performance tests—creating stress and measuring throughput (requests per second).
We want to extend the test tool with a profiling feature: specify the number of requests sent per second.
E.g., a performance test shows the server handles $1000$ requests per second.
We want the test tool to send requests at a specified rate, say $500$, $200$, $20$, or even $0.2$ requests per second (one request every 5 seconds).
Such a profiling tool allows exploring the server state under various load conditions: CPU, memory, threads depending on the number of requests received.</p>
<p>The test tool may divide 1 second into $100$ parts, each $20$ milliseconds.
Suppose we specify $230$ requests per second: then during every part, $2.3$ requests must be sent on average.
In other words, the tool must send 2 requests in most parts and 3 in some parts.
We need to choose which $30$ parts get the extra request; ${\cal PD}(30, 100)$ yields that array (a $1$ in cell $i$ means part $i$ gets 3 requests).</p>
<h3 id="why-naive-approaches-fail">Why naive approaches fail</h3>
<p>A natural idea is to place ones at multiples of $n/a$, e.g. <code>[1 if (i * a) % n &lt; a else 0 for i in range(n)]</code>, or to use <code>round(i * a / n)</code> to decide. Such formulas can produce wrong counts (off-by-one), clusters at the boundaries, or gaps that differ by more than one. Another approach—repeatedly choosing the “emptiest” gap—avoids clustering but is harder to implement correctly and lacks the clean recurrence we want. ${\cal PD}$ gives the exact, unique fairest distribution in a few lines.</p>
<p>We present the general solution ${\cal PD}$ to the problem—for any specified input in the above examples, ${\cal PD}$ produces the exact solution.
Any probabilistic or approximation solutions do not achieve the required exactness and are usually more complicated.
The algorithm ${\cal PD}$ is simple, has a clear correctness proof, and admits $O(n)$ time and space complexity.
Moreover, it has a direct relation to Euclid&rsquo;s algorithm for computing the Greatest Common Divisor, denoted here by ${\cal GCD}$.</p>
<h3 id="notation">Notation</h3>
<p><em>POST</em> denotes a condition that the procedure guarantees will hold after the call.</p>
<h3 id="euclids-algorithm-cal-gcd">Euclid&rsquo;s Algorithm ${\cal GCD}$</h3>
<ul>
<li>POST: $res = {\cal GCD}(a, n)$.</li>
</ul>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-python" data-lang="python"><span style="display:flex;"><span><span style="color:#66d9ef">def</span> <span style="color:#a6e22e">gcd</span>(a: int, n: int) <span style="color:#f92672">-&gt;</span> int:
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">assert</span> <span style="color:#ae81ff">0</span> <span style="color:#f92672">&lt;=</span> a <span style="color:#f92672">&lt;=</span> n
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> res <span style="color:#f92672">=</span> n
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">if</span> a <span style="color:#f92672">&gt;</span> <span style="color:#ae81ff">0</span>:
</span></span><span style="display:flex;"><span> res <span style="color:#f92672">=</span> gcd(n <span style="color:#f92672">%</span> a, a)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">return</span> res
</span></span></code></pre></div><h3 id="deterministic-algorithm-of-perfect-distribution-cal-pd">Deterministic algorithm of perfect distribution ${\cal PD}$</h3>
<p>The recurrence mirrors Euclid&rsquo;s algorithm: ${\cal PD}(a, n)$ calls ${\cal PD}(n \bmod a, a)$, so the recursion depth is $O(\log \min(a, n))$ and total time is $O(n)$.</p>
<ul>
<li>POST: size of $res$ is $n$.</li>
<li>POST: $\forall i,, res[i] \in {0, 1}$.</li>
<li>POST: $\sum_{i=0}^{n-1} res[i] = a$ (exactly $a$ ones).</li>
<li>POST: $res$ is perfectly distributed (gaps between consecutive ones differ by at most 1).</li>
</ul>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-python" data-lang="python"><span style="display:flex;"><span><span style="color:#66d9ef">def</span> <span style="color:#a6e22e">pd</span>(a: int, n: int) <span style="color:#f92672">-&gt;</span> list[int]:
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">assert</span> <span style="color:#ae81ff">0</span> <span style="color:#f92672">&lt;=</span> a <span style="color:#f92672">&lt;=</span> n
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> res <span style="color:#f92672">=</span> [<span style="color:#ae81ff">0</span>] <span style="color:#f92672">*</span> n
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">if</span> a <span style="color:#f92672">&gt;</span> <span style="color:#ae81ff">0</span>:
</span></span><span style="display:flex;"><span> steps <span style="color:#f92672">=</span> pd(n <span style="color:#f92672">%</span> a, a)
</span></span><span style="display:flex;"><span> step <span style="color:#f92672">=</span> n <span style="color:#f92672">//</span> a
</span></span><span style="display:flex;"><span> ofs <span style="color:#f92672">=</span> <span style="color:#ae81ff">0</span>
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">for</span> i <span style="color:#f92672">in</span> range(a):
</span></span><span style="display:flex;"><span> res[ofs] <span style="color:#f92672">=</span> <span style="color:#ae81ff">1</span>
</span></span><span style="display:flex;"><span> ofs <span style="color:#f92672">+=</span> step <span style="color:#f92672">+</span> steps[i]
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">return</span> res
</span></span></code></pre></div><p><strong>Why it works.</strong> The algorithm treats $n$ positions as $a$ “blocks” of size $\lfloor n/a \rfloor$ or $\lceil n/a \rceil$. The recursive call ${\cal PD}(n \bmod a, a)$ decides which blocks get the extra slot (the remainder). Each block is filled by either repeating a perfect distribution of ones in a sub-interval (when $a \le n/2$) or by inverting zeros when $a &gt; n/2$. The recurrence ensures that at every level, the pattern stays uniform—no block gets more than one extra slot, so gaps never differ by more than one.</p>
<p><strong>Optimality.</strong> The perfect distribution (gaps differ by at most 1) is unique up to the choice of which gaps are $\lfloor (n-a)/a \rfloor$ and which are $\lceil (n-a)/a \rceil$. The algorithm constructs this by induction: the base case $a=0$ is trivial; for $a&gt;0$, the recursive call yields a perfect distribution for the “remainder” subproblem, and the interleaving step preserves the gap invariant.</p>
<h3 id="example-cal-pd2-10-a--2-n--10-so-n---a--8-zeros">Example. ${\cal PD}(2, 10)$: $a = 2$, $n = 10$, so $n - a = 8$ zeros</h3>
<p>We want to mix $2$ ones and $8$ zeros.
The recursive call ${\cal PD}(0, 2)$ returns $[0, 0] = 0^2$, which is assigned to $arr$.
Then the array $res$ is filled as follows: $[(1, 0, 0, 0, 0), (1, 0, 0, 0, 0)] = (1, 0^4)^2$, which is returned by ${\cal PD}(2, 10)$.</p>
<h3 id="example-cal-pd8-10-a--8-n--10-so-n---a--2-zeros">Example. ${\cal PD}(8, 10)$: $a = 8$, $n = 10$, so $n - a = 2$ zeros</h3>
<p>We want to mix $8$ ones and $2$ zeros.
The recursive call ${\cal PD}(2, 8)$ returns $[1, 0, 0, 0, 1, 0, 0, 0] = (1, 0^3)^2$, which is assigned to $arr$.
Then the array $res$ is filled as follows: $[(1, 0, 1, 1, 1), (1, 0, 1, 1, 1)] = (1, 0, 1^3)^2$, which is returned by ${\cal PD}(8, 10)$.</p>
<h3 id="examples">Examples.</h3>
<ul>
<li>
<p>${\cal PD}(1, 10) : [1, 0, \ldots, 0] = 1, 0^9$</p>
</li>
<li>
<p>${\cal PD}(2, 10) : [1, 0, 0, 0, 0, 1, 0, 0, 0, 0] = 1, 0^4 , 1, 0^4$</p>
</li>
<li>
<p>${\cal PD}(3, 10) : [1, 0, 0, 1, 0, 0, 1, 0, 0, 0] = 1, 0^2 , 1, 0^2 , 1, 0^3$ — visual: <code>1 _ _ 1 _ _ 1 _ _ _</code> (gaps between 1s: 2, 2, 3)</p>
</li>
<li>
<p>${\cal PD}(4, 10) : [1, 0, 0, 1, 0, 1, 0, 0, 1, 0] = 1, 0^2 , 1, 0, 1, 0^2 , 1, 0$ $= (1, 0^2 , 1, 0)^2$</p>
</li>
<li>
<p>${\cal PD}(5, 10) : [1, 0, 1, 0, 1, 0, 1, 0, 1, 0] = (1, 0)^5$</p>
</li>
<li>
<p>${\cal PD}(6, 10) : [1, 0, 1, 1, 0, 1, 0, 1, 1, 0] = 1, 0, 1^2 , 0, 1, 0, 1^2 , 0$ $ = (1, 0, 1^2 , 0)^2$</p>
</li>
<li>
<p>${\cal PD}(0, 2) : [0, 0] = 0^2$</p>
</li>
<li>
<p>${\cal PD}(2, 6) : [1, 0, 0, 1, 0, 0] = 1, 0^2 , 1, 0^2 = (1, 0^2)^2$</p>
</li>
<li>
<p>${\cal PD}(6, 8) : [1, 0, 1, 1, 1, 0, 1, 1] = 1, 0, 1^3, 0, 1^2 = (1, 0, 1^2)^2$</p>
</li>
<li>
<p>${\cal PD}(8, 14) : [1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0] = (1, 0, 1, 1, 0, 1, 0)^2$ $ = ((1, 0, 1)^2 , 0)^2$</p>
</li>
</ul>
<h3 id="alternative-formulation-subtraction-based-slow-versions">Alternative formulation: subtraction-based (slow) versions</h3>
<p>The same recurrence can be expressed using subtraction instead of modulo, which makes the symmetry with Euclid&rsquo;s algorithm more explicit. These versions have the same recursion structure but do more work per step.</p>
<p><strong>Slow GCD (subtraction-based):</strong></p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-python" data-lang="python"><span style="display:flex;"><span><span style="color:#66d9ef">def</span> <span style="color:#a6e22e">gcd</span>(a: int, n: int) <span style="color:#f92672">-&gt;</span> int:
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">assert</span> <span style="color:#ae81ff">0</span> <span style="color:#f92672">&lt;=</span> a <span style="color:#f92672">&lt;=</span> n
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> res <span style="color:#f92672">=</span> n
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">if</span> a <span style="color:#f92672">&gt;</span> <span style="color:#ae81ff">0</span>:
</span></span><span style="display:flex;"><span> b <span style="color:#f92672">=</span> n <span style="color:#f92672">-</span> a
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">if</span> b <span style="color:#f92672">&gt;</span> a:
</span></span><span style="display:flex;"><span> res <span style="color:#f92672">=</span> gcd(a, b)
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">else</span>:
</span></span><span style="display:flex;"><span> res <span style="color:#f92672">=</span> gcd(b, a)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">return</span> res
</span></span></code></pre></div><p><strong>Slow PD (subtraction-based):</strong></p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-python" data-lang="python"><span style="display:flex;"><span><span style="color:#66d9ef">def</span> <span style="color:#a6e22e">pd</span>(a: int, n: int) <span style="color:#f92672">-&gt;</span> list[int]:
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">assert</span> <span style="color:#ae81ff">0</span> <span style="color:#f92672">&lt;=</span> a <span style="color:#f92672">&lt;=</span> n
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> res <span style="color:#f92672">=</span> [<span style="color:#ae81ff">0</span>] <span style="color:#f92672">*</span> n
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">if</span> a <span style="color:#f92672">&gt;</span> <span style="color:#ae81ff">0</span>:
</span></span><span style="display:flex;"><span> ofs <span style="color:#f92672">=</span> <span style="color:#ae81ff">0</span>
</span></span><span style="display:flex;"><span> b <span style="color:#f92672">=</span> n <span style="color:#f92672">-</span> a
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">if</span> b <span style="color:#f92672">&gt;</span> a:
</span></span><span style="display:flex;"><span> arr <span style="color:#f92672">=</span> pd(a, b)
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">for</span> i <span style="color:#f92672">in</span> range(b):
</span></span><span style="display:flex;"><span> res[ofs] <span style="color:#f92672">=</span> arr[i]
</span></span><span style="display:flex;"><span> ofs <span style="color:#f92672">+=</span> <span style="color:#ae81ff">1</span> <span style="color:#f92672">+</span> arr[i]
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">else</span>:
</span></span><span style="display:flex;"><span> arr <span style="color:#f92672">=</span> pd(b, a)
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">for</span> i <span style="color:#f92672">in</span> range(a):
</span></span><span style="display:flex;"><span> res[ofs] <span style="color:#f92672">=</span> <span style="color:#ae81ff">1</span> <span style="color:#f92672">-</span> arr[i]
</span></span><span style="display:flex;"><span> ofs <span style="color:#f92672">+=</span> <span style="color:#ae81ff">2</span> <span style="color:#f92672">-</span> arr[i]
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">return</span> res
</span></span></code></pre></div></description>
</item>
<item>
<title>Binomial Coefficients Modulo a Prime: Fermat's Theorem and the Non-Adjacent Selection Problem</title>
<link>/post/binomial-modulo-prime/</link>
<pubDate>Sat, 08 Jul 2017 07:29:43 +0000</pubDate>
<guid>/post/binomial-modulo-prime/</guid>
<description><p>In the <a href="/post/efficient-implementation-non-adjacent-selection/">previous post</a>, we implemented the closed form $F_{n,m} = \binom{n-m+1}{m}$ using Python&rsquo;s <code>math.factorial</code>, and with <code>scipy</code> and <code>sympy</code>. Here we cover the common competitive-programming case: computing the answer <strong>modulo a large prime</strong> $M$ (e.g. $M = 10^9+7$).</p>
<h2 id="why-modulo">Why modulo?</h2>
<p>In counting problems, the result can be huge even for moderate input. Often the problem asks for the answer modulo a big prime so that it fits in a standard integer type. We could compute the full number and then take the remainder, but that forces expensive long-integer arithmetic. Computing <strong>everything</strong> modulo $M$ from the start is much faster.</p>
<h2 id="from-binomials-to-modular-inverses">From binomials to modular inverses</h2>
<p>We have $F_{n,m} = \binom{n-m+1}{m} = \frac{(n-m+1)!}{m!,(n-2m+1)!}$. To compute this mod $M$, we need factorials mod $M$ and division mod $M$. Division mod $M$ is multiplication by the <strong>modular inverse</strong>: for prime $M$ and $0 &lt; x &lt; M$, the inverse of $x$ is $x^{M-2} \bmod M$ by <a href="https://en.wikipedia.org/wiki/Fermat%27s_little_theorem" target="_blank" rel="noopener">Fermat&rsquo;s little theorem</a>. In Python we can use <code>pow(x, M - 2, M)</code>.</p>
<h2 id="implementation">Implementation</h2>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-python" data-lang="python"><span style="display:flex;"><span><span style="color:#f92672">import</span> functools
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>M <span style="color:#f92672">=</span> <span style="color:#ae81ff">10</span><span style="color:#f92672">**</span><span style="color:#ae81ff">9</span> <span style="color:#f92672">+</span> <span style="color:#ae81ff">7</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">def</span> <span style="color:#a6e22e">f_binom_mod</span>(n, m):
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">assert</span> n <span style="color:#f92672">&gt;=</span> <span style="color:#ae81ff">0</span> <span style="color:#f92672">and</span> m <span style="color:#f92672">&gt;=</span> <span style="color:#ae81ff">0</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">if</span> n <span style="color:#f92672">+</span> <span style="color:#ae81ff">1</span> <span style="color:#f92672">&lt;</span> <span style="color:#ae81ff">2</span><span style="color:#f92672">*</span>m:
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">return</span> <span style="color:#ae81ff">0</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">return</span> binom_mod(n <span style="color:#f92672">-</span> m <span style="color:#f92672">+</span> <span style="color:#ae81ff">1</span>, m)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">def</span> <span style="color:#a6e22e">binom_mod</span>(n, m):
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">assert</span> <span style="color:#ae81ff">0</span> <span style="color:#f92672">&lt;=</span> m <span style="color:#f92672">&lt;=</span> n
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">return</span> ((fact_mod(n) <span style="color:#f92672">*</span> inv_mod(fact_mod(m))) <span style="color:#f92672">%</span> M <span style="color:#f92672">*</span> inv_mod(fact_mod(n <span style="color:#f92672">-</span> m))) <span style="color:#f92672">%</span> M
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">@functools.lru_cache</span>(maxsize<span style="color:#f92672">=</span><span style="color:#66d9ef">None</span>)
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">def</span> <span style="color:#a6e22e">fact_mod</span>(m):
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">if</span> m <span style="color:#f92672">&lt;=</span> <span style="color:#ae81ff">1</span>:
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">return</span> <span style="color:#ae81ff">1</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">return</span> (m <span style="color:#f92672">*</span> fact_mod(m <span style="color:#f92672">-</span> <span style="color:#ae81ff">1</span>)) <span style="color:#f92672">%</span> M
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">def</span> <span style="color:#a6e22e">inv_mod</span>(x):
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">return</span> pow(x, M <span style="color:#f92672">-</span> <span style="color:#ae81ff">2</span>, M)
</span></span></code></pre></div><p>All operations stay in the ring of integers mod $M$. The only non-obvious part is modular division: we replace division by $d$ with multiplication by <code>inv_mod(d)</code> using Fermat&rsquo;s little theorem.</p>
<h2 id="benchmarks">Benchmarks</h2>
<p>Compared to computing the full binomial and then taking the remainder, the modular version avoids long arithmetic and is much faster:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-python" data-lang="python"><span style="display:flex;"><span>fact_mod(<span style="color:#ae81ff">10000</span>) <span style="color:#75715e"># for caching factorials</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>funcs <span style="color:#f92672">=</span> [f_binom_mod, f_binom, f_sci, f_sym]
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>test(<span style="color:#ae81ff">10000</span>, <span style="color:#ae81ff">1000</span>, funcs)
</span></span><span style="display:flex;"><span>test(<span style="color:#ae81ff">10000</span>, <span style="color:#ae81ff">2000</span>, funcs)
</span></span><span style="display:flex;"><span>test(<span style="color:#ae81ff">10000</span>, <span style="color:#ae81ff">3000</span>, funcs)
</span></span></code></pre></div><p>Example output:</p>
<pre tabindex="0"><code>f(10000,1000): 450169549
f_binom_mod: 0.0000 sec, x 1.00
f_binom: 0.0073 sec, x 337.60
f_sci: 0.0011 sec, x 49.33
f_sym: 0.0076 sec, x 353.22
f(10000,2000): 75198348
f_binom_mod: 0.0000 sec, x 1.00
f_binom: 0.0063 sec, x 368.94
f_sci: 0.0026 sec, x 153.33
f_sym: 0.0053 sec, x 308.93
f(10000,3000): 679286557
f_binom_mod: 0.0000 sec, x 1.00
f_binom: 0.0060 sec, x 361.12
f_sci: 0.0056 sec, x 338.13
f_sym: 0.0053 sec, x 319.02
</code></pre><p>The same pattern—factorials mod $M$ plus Fermat-based inverses—works for any combinatorial formula that can be written in terms of factorials and binomials modulo a prime.</p>
</description>
</item>
<item>
<title>Efficient Implementation of the Non-Adjacent Selection Formula</title>
<link>/post/efficient-implementation-non-adjacent-selection/</link>
<pubDate>Fri, 07 Jul 2017 07:29:43 +0000</pubDate>
<guid>/post/efficient-implementation-non-adjacent-selection/</guid>
<description><p>In the <a href="/post/two-var-recursive-func/">previous post</a>, we derived the closed form for the non-adjacent selection problem:</p>
<p>$$ F_{n, m} = {n - m + 1 \choose m} $$</p>
<p>Now we discuss how to implement this efficiently in Python—from a simple factorial-based solution to library implementations. For the common case of computing the answer <strong>modulo a large prime</strong> (e.g. in competitive programming), see the <a href="/post/binomial-modulo-prime/">next post</a>.</p>
<h2 id="fast-solutions-based-on-binomials">Fast Solutions Based on Binomials</h2>
<p>We can reflect the closed form in very trivial Python code:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-Python" data-lang="Python"><span style="display:flex;"><span><span style="color:#f92672">import</span> math
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">def</span> <span style="color:#a6e22e">f_binom</span>(n, m):
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">assert</span> n <span style="color:#f92672">&gt;=</span> <span style="color:#ae81ff">0</span> <span style="color:#f92672">and</span> m <span style="color:#f92672">&gt;=</span> <span style="color:#ae81ff">0</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">if</span> n <span style="color:#f92672">+</span> <span style="color:#ae81ff">1</span> <span style="color:#f92672">&lt;</span> <span style="color:#ae81ff">2</span><span style="color:#f92672">*</span>m:
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">return</span> <span style="color:#ae81ff">0</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">return</span> binom(n <span style="color:#f92672">-</span> m <span style="color:#f92672">+</span> <span style="color:#ae81ff">1</span>, m)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">def</span> <span style="color:#a6e22e">binom</span>(n, m):
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">assert</span> <span style="color:#ae81ff">0</span> <span style="color:#f92672">&lt;=</span> m <span style="color:#f92672">&lt;=</span> n
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">return</span> math<span style="color:#f92672">.</span>factorial(n) <span style="color:#f92672">//</span> math<span style="color:#f92672">.</span>factorial(m) <span style="color:#f92672">//</span> math<span style="color:#f92672">.</span>factorial(n <span style="color:#f92672">-</span> m)
</span></span></code></pre></div><p>This implementation overperforms significantly the initial DP and memoization solutions from <a href="/post/intro-to-dp/">Introduction to Dynamic Programming and Memoization</a>.
A naive implementation of <code>math.factorial()</code> might make $n$ multiplications.
This could still be faster than doing $\Theta(n)$ additions in DP approach.</p>
<p>The actual implementation of <code>math.factorial()</code> is written in C
and probably has precomputed results for some range of $n$
and might even cache the results for bigger $n$.</p>
<h2 id="implementations-based-on-scipy-and-sympy-libraries">Implementations Based on <code>scipy</code> and <code>sympy</code> Libraries</h2>
<p>Several third party libraries provide a functionality to compute binomial coefficients.
Let&rsquo;s take a look at <code>scipy</code> and <code>sympy</code>.</p>
<p>We can install both of them using <code>pip</code>-package manager:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-bash" data-lang="bash"><span style="display:flex;"><span>pip install scipy sympy
</span></span></code></pre></div><p>We can easily write two implementations of $F_{n,m}$ which will call <code>scipy.special.comb()</code> or <code>sympy.binomial()</code> functions:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-Python" data-lang="Python"><span style="display:flex;"><span><span style="color:#f92672">import</span> scipy.special
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">def</span> <span style="color:#a6e22e">f_sci</span>(n, m):
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">assert</span> n <span style="color:#f92672">&gt;=</span> <span style="color:#ae81ff">0</span> <span style="color:#f92672">and</span> m <span style="color:#f92672">&gt;=</span> <span style="color:#ae81ff">0</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">if</span> n <span style="color:#f92672">+</span> <span style="color:#ae81ff">1</span> <span style="color:#f92672">&lt;</span> <span style="color:#ae81ff">2</span><span style="color:#f92672">*</span>m:
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">return</span> <span style="color:#ae81ff">0</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">return</span> scipy<span style="color:#f92672">.</span>special<span style="color:#f92672">.</span>comb(n <span style="color:#f92672">-</span> m <span style="color:#f92672">+</span> <span style="color:#ae81ff">1</span>, m, exact<span style="color:#f92672">=</span><span style="color:#66d9ef">True</span>)
</span></span></code></pre></div><p>The second one is very similar to the first one:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-Python" data-lang="Python"><span style="display:flex;"><span><span style="color:#f92672">import</span> sympy
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">def</span> <span style="color:#a6e22e">f_sym</span>(n, m):
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">assert</span> n <span style="color:#f92672">&gt;=</span> <span style="color:#ae81ff">0</span> <span style="color:#f92672">and</span> m <span style="color:#f92672">&gt;=</span> <span style="color:#ae81ff">0</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">if</span> n <span style="color:#f92672">+</span> <span style="color:#ae81ff">1</span> <span style="color:#f92672">&lt;</span> <span style="color:#ae81ff">2</span><span style="color:#f92672">*</span>m:
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">return</span> <span style="color:#ae81ff">0</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">return</span> sympy<span style="color:#f92672">.</span>binomial(n <span style="color:#f92672">-</span> m <span style="color:#f92672">+</span> <span style="color:#ae81ff">1</span>, m)
</span></span></code></pre></div><p>We can use the same <code>test()</code> helper function that we defined in <a href="/post/intro-to-dp/">Introduction to Dynamic Programming and Memoization</a>.
Let&rsquo;s run it on all the 5 implementations:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-python" data-lang="python"><span style="display:flex;"><span>funcs <span style="color:#f92672">=</span> [f_mem, f_dp, f_binom, f_sci, f_sym]
</span></span><span style="display:flex;"><span>test(<span style="color:#ae81ff">6000</span>, <span style="color:#ae81ff">2000</span>, funcs)
</span></span></code></pre></div><p>It will print something similar to following output:</p>
<pre tabindex="0"><code>f(6000,2000): 192496093
f_mem: 6.7195 sec, x 4195.10
f_dp: 5.3249 sec, x 3324.43
f_binom: 0.0016 sec, x 1.00
f_sci: 0.0021 sec, x 1.32
f_sym: 0.0043 sec, x 2.69
</code></pre><p>The first two methods, which are based on memoization and DP, are much slower than the last three,
which are based on the binomial coefficients.</p>
<h2 id="the-intuition-for-the-time-complexity-analysis">The Intuition for the Time Complexity Analysis</h2>
<p>DP and memoization makes $O(n^2)$ of &ldquo;addition&rdquo; operations over long integers.
The long integers are bounded by $F_{n,m}$ value, which could be bounded by $2^n$.
One &ldquo;addition&rdquo; operation takes $O(N)$ time for $N$-digit integer input.
For our case $N$ could be bounded by $ O(\log 2^n)$ $ = O(n)$.
So the total time complexity is bounded by
$ O(n^2 \cdot N) $
$ = O(n^2 \cdot \log 2^n) $
$ = O(n^2 \cdot n) $
$ = O(n^3)$.</p>
<p>The binomial based solutions make $O(n)$ &ldquo;multiplication&rdquo; operations over long integers
The long integers could be bounded by $O(n!)$ $ = O(n^n)$.
The &ldquo;multiplication&rdquo; operation could be implemented in a naive way which runs $O(N^2)$ in time and is used for a small input.
But it also has a more advanced implementation, which takes $O(N^{\log_2 3})$ $ = O(N^{1.59})$ and is used on big integers.
Note that here $N$ denotes the number of digits in the input long integers for multiplication.
In this case, $N$ is bounded by
$ O(\log n!) $
$ = O(\log (n^n)) $
$ = O(n \log n) $.
The total time complexity of the binomial based implementations is bounded by
$ O\left(n \cdot N^{\log_2 3}\right) $
$ = O\left(n \cdot (\log n!)^{\log_2 3}\right)$
$ = O\left(n \cdot (n \log n)^{1.59}\right)$
$ = O\left(n^{2.59} \cdot (\log n)^{1.59}\right)$.</p>
<p>This is not really a formal proof, but it gives some intuition why the last approach overperforms the former one.
In practice, the results of factorial computation are cached,
therefore we observe even bigger gap in performance (yeahh again not formal claim, just an intuition).</p>
<p>You can play with running tests on different $n$ and $m$.
What I saw that actually there is no clear winner between the last 3 implementations.
Probably, the most of the time is spent on the long arithmetic computation.</p>
<p>When the problem asks for the answer <strong>modulo a large prime</strong> (e.g. $10^9+7$), computing everything mod $M$ from the start is much faster than using long integers. We cover that in a <a href="/post/binomial-modulo-prime/">separate post</a>: binomial coefficients modulo a prime using Fermat&rsquo;s little theorem.</p>
</description>
</item>
<item>
<title>Cracking Multivariate Recursive Equations Using Generating Functions</title>
<link>/post/two-var-recursive-func/</link>
<pubDate>Thu, 06 Jul 2017 07:29:43 +0000</pubDate>
<guid>/post/two-var-recursive-func/</guid>
<description><p>In this post, we return back to the combinatorial problem discussed in <a href="/post/intro-to-dp/">Introduction to Dynamic Programming and Memoization</a> post.
We will show that generating functions may work great not only for single variable case (see <a href="/post/gen-func-art/">The Art of Generating Functions</a>),
but also could be very useful for hacking two-variable relations (and of course, in general for multivariate case too).</p>
<p>For making the post self-contained, we repeat the problem definition here.</p>
<h2 id="the-problem">The Problem</h2>