-
Notifications
You must be signed in to change notification settings - Fork 34
/
modular_fibonacci_polynomial_2.pl
executable file
·56 lines (38 loc) · 1.29 KB
/
modular_fibonacci_polynomial_2.pl
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
#!/usr/bin/perl
# Daniel "Trizen" Șuteu
# Date: 11 October 2017
# https://github.com/trizen
# Algorithm for computing a Fibonacci polynomial modulo m.
# (Sum_{k=1..n} (fibonacci(k) * x^k)) (mod m)
# See also:
# https://projecteuler.net/problem=435
use 5.020;
use strict;
use warnings;
use experimental qw(signatures);
use ntheory qw(addmod mulmod powmod factor_exp chinese);
sub modular_fibonacci_polynomial ($n, $x, $m) {
my @chinese;
foreach my $p (factor_exp($m)) {
my $pp = $p->[0]**$p->[1];
my $sum = 0;
my ($f1, $f2) = (0, 1);
my @array;
foreach my $k (1 .. $n) {
$sum = addmod($sum, mulmod($f2, powmod($x, $k, $pp), $pp), $pp);
push @array, $sum;
($f1, $f2) = ($f2, addmod($f1, $f2, $pp));
if ($f1 == 0 and $f2 == 1 and $k > 20 and
join(' ', @array[9 .. $#array/2])
eq join(' ', @array[$#array/2 + 10 .. $#array])
) {
$sum = $array[($n % $k) - 1];
last;
}
}
push @chinese, [$sum, $pp];
}
return chinese(@chinese);
}
say modular_fibonacci_polynomial(7, 11, 100000); #=> 57683
say modular_fibonacci_polynomial(10**15, 13, 6227020800); #=> 4631902275