-
Notifications
You must be signed in to change notification settings - Fork 0
/
spoj_fibandnonfib.cpp
74 lines (66 loc) · 1.16 KB
/
spoj_fibandnonfib.cpp
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
#include <cstdio>
#include <unordered_map>
using namespace std;
typedef long long int ll;
ll M = 1000000007;
ll mulmod(ll a, ll b) //modular multiplication
{
ll x = 0;
ll y = a%M;
while(b>0)
{
if(b%2)
x = (x+y)%M;
y = (y+y)%M;
b/=2;
}
return x%M;
}
ll modulo(ll a, ll b) //modular exponentiation
{
ll x = 1;
ll y = a;
while(b)
{
if(b%2)
x = mulmod(x,y);
y = mulmod(y,y);
b/=2;
}
return x%M;
}
unordered_map<ll,ll> Fib;
ll fibo(ll n) //n+1 th fibonacci number
{
if(n<2)
return 1;
if(Fib.find(n) != Fib.end())
return Fib[n];
Fib[n] = (fibo((n+1) / 2)*fibo(n/2) + fibo((n-1) / 2)*fibo((n-2) / 2)) % M;
return Fib[n];
}
ll nonfibo(ll n) //nth non-fibonacci number
{
ll a = 1, b = 2, c = 3;
while(n>0)
{
a = b;
b = c;
c = a+b;
n-=(c-b-1);
}
n+=(c-b-1);
return n + b;
}
int main()
{
ll t;
scanf("%lld",&t);
while(t--)
{
ll n;
scanf("%lld",&n);
printf("%lld\n",modulo(nonfibo(n),fibo(n-1)));
}
return 0;
}