-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathmodular_binomial.pl
More file actions
executable file
·47 lines (34 loc) · 925 Bytes
/
modular_binomial.pl
File metadata and controls
executable file
·47 lines (34 loc) · 925 Bytes
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
#!/usr/bin/perl
# Author: Daniel "Trizen" Șuteu
# License: GPLv3
# Date: 08 February 2017
# Website: https://github.com/trizen
# Algorithm for binomial(n, k) mod m.
use 5.020;
use strict;
use warnings;
use experimental qw(signatures);
use ntheory qw(forprimes powmod vecsum todigits);
sub factorial_power ($n, $p) {
($n - vecsum(todigits($n, $p))) / ($p - 1);
}
sub modular_binomial ($n, $k, $m) {
my $j = $n - $k;
my $prod = 1;
forprimes {
my $p = factorial_power($n, $_);
if ($_ <= $k) {
$p -= factorial_power($k, $_);
}
if ($_ <= $j) {
$p -= factorial_power($j, $_);
}
if ($p > 0) {
$prod *= ($p == 1) ? ($_ % $m) : powmod($_, $p, $m);
$prod %= $m;
}
} $n;
return $prod;
}
say modular_binomial(100, 50, 139); #=> 71
say modular_binomial(124, 42, 1234567); #=> 395154