# CodeForces-450B Jzzhu and Sequences【数列+矩阵快速幂】

time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

Jzzhu has invented a kind of sequences, they meet the following property:

You are given x and y, please calculate fn modulo 1000000007 (109 + 7).

Input

The first line contains two integers x and y (|x|, |y| ≤ 10^9). The second line contains a single integer n (1 ≤ n ≤ 2·10^9).

Output

Output a single integer representing fn modulo 1000000007 (10^9 + 7).

Examples
input
Copy
2 3
3

output
1

input
Copy
0 -1
2

output
1000000006

Note

In the first sample, f2 = f1 + f3, 3 = 2 + f3, f3 = 1.

In the second sample, f2 =  - 1;  - 1 modulo (10^9 + 7) equals (10^9 + 6).

方法一：

依据题意，fi+1=fi-fi-1。故：

f1=x, f2=y, f3=y-x,f4=-x, f5=-y, f6=x-y, f7=x, f8=y, ......

这个数列每6项值出现循环。

以上分析可得到f0=f6=x-y。

方法二：

用矩阵快速幂实现。

程序中都是套路。

AC的C++语言程序（方法一）如下：

/* CodeForces-450B Jzzhu and Sequences */

#include <iostream>

using namespace std;

const int MOD = 1000000007;
const int N = 6;

int ans[N];

int main()
{
int x, y, n;

cin >> x >> y >> n;

// Init ans
ans[0] = x - y;
ans[1] = x;
ans[2] = y;
ans[3] = y - x;
ans[4] = -x;
ans[5] = - y;

int result = ans[n % N];
if(result >= 0)
cout << result % MOD << endl;
else
cout << (result % MOD + MOD) % MOD << endl;

return 0;
}



AC的C++语言程序（方法二）如下：

/* CodeForces-450B Jzzhu and Sequences */

#include <iostream>
#include <string.h>

using namespace std;

typedef long long LL;

const int MOD = 1e9+7;
const int N = 2;

struct Matrix
{
LL m[N][N];

Matrix()
{
memset(m, 0, sizeof(m));
}

// 矩阵相乘
Matrix operator * (const Matrix& y)
{
Matrix z;

for(int i=0; i<N; i++)
for(int j=0; j<N; j++)
for(int k=0; k<N; k++) {
z.m[i][j] += m[i][k] * y.m[k][j] % MOD;
z.m[i][j] %= MOD;
}

return z;
}
};

// 矩阵快速幂
Matrix Matrix_Powmul(Matrix x, int m)
{
Matrix z;
z.m[0][1] = z.m[1][0] = 0;
z.m[0][0] = z.m[1][1] = 1;

while(m) {
if(m & 1)
z = z * x;
x = x * x;
m >>= 1;
}

return z;
}

int main()
{
int x, y, n;
int result;

cin >> x >> y >> n;

if(n == 1)
result = x;
else if(n == 2)
result = y;
else {
Matrix a;
a.m[0][0] = 0;
a.m[1][0] = -1;
a.m[0][1] = a.m[1][1] =1;

Matrix t = Matrix_Powmul(a, n - 2);

result = (x * t.m[1][0] + y * t.m[1][1]) % MOD;
}

if(result >= 0)
cout << result % MOD << endl;
else
cout << (result % MOD + MOD) % MOD << endl;

return 0;
}



#### 【矩阵快速幂 】Codeforces 450B - Jzzhu and Sequences （公式转化）

2015-04-11 20:59:44

#### Codeforces 691E Xor-sequences【矩阵快速幂，好题】

2016-07-15 21:01:26

#### B. Jzzhu and Sequences

2014-08-06 22:18:40

#### CodeForces-450B Jzzhu and Sequences

2015-08-11 19:05:30

#### Jzzhu and Sequences - CF 450B 矩阵快速幂版

2014-07-20 11:36:48

#### Codeforces Jzzhu and Sequences(循环节)

2014-07-20 09:29:14

#### Jzzhu and Sequences 【矩阵快速幂】

2015-03-23 12:20:21

#### CodeForces450B Jzzhu and Sequences (矩阵快速幂)

2017-08-10 19:36:29

#### hdu-4686 Jzzhu and Sequences 【矩阵快速幂】

2016-04-19 17:01:25

#### （CF#257)B. Jzzhu and Sequences

2014-07-20 08:05:50