codeforces round 450 div2 b.jzzhu and sequences

B. 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 _f__n_ modulo 1000000007 (109 + 7).

Input

The first line contains two integers _x_ and _y_ (|_x_|, |_y_| ≤ 109). The second line contains a single integer _n_ (1 ≤ _n_ ≤ 2·109).

Output

Output a single integer representing _f__n_ modulo 1000000007 (109 + 7).

Examples

input

2 3
3

output

1

input

0 -1
2

output

1000000006

Note

In the first sample, _f_2 = _f_1 + _f_3, 3 = 2 + _f_3, _f_3 = 1.

In the second sample, _f_2 =  - 1;  - 1 modulo (109 + 7) equals (109 + 6).

题解

使用矩阵快速幂,构造2*2矩阵从左到右从上到下为 1,1,-1,0。代码如下:

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

#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
#include <cmath>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <utility>
#define ll long long

using namespace std ;

const ll MOD = 1e9+7 ;
const int maxn = 2 ;

struct {
int m[maxn][maxn] ;
}mat ;

matrix operator *(matrix a , matrix b){
matrix res ;
for ( int i = 0 ; i < maxn ; i ++ ){
for ( int j = 0 ; j < maxn ; j ++ ){
ll temp = 0 ;
for ( int k = 0 ; k < maxn ; k ++ ){
temp += (a.m[i][k] % MOD * b.m[k][j] % MOD) % MOD ;
}
res.m[i][j] = temp % MOD ;
}
}
return res ;
}

void init(){
for ( int i = 0 ; i < maxn ; i ++ ){
mat.m[i][i] = 1 ;
}
return ;
}

matrix quick_pow(matrix a, ll n){
matrix ans = mat ;
while (n){
if (n & 1){
ans = ans * a ;
}
a = a * a ;
n >>= 1 ;
}
return ans ;
}

int main(){
ll x , y , n ;
while ( cin >> x >> y >> n ){
if ( n == 1 ){
cout << (x % MOD + MOD) % MOD << endl ;
}else if ( n == 2 ){
cout << (y % MOD + MOD) % MOD << endl ;
}else{
init() ;
matrix temp ;
temp.m[0][0] = 1 , temp.m[0][1] = 1 ;
temp.m[1][0] = -1 , temp.m[1][1] = 0 ;
temp = quick_pow(temp , n - 2) ;
matrix ans ;
ans.m[0][0] = y , ans.m[0][1] = x ;
ans = ans * temp ;
cout << (ans.m[0][0] % MOD + MOD) % MOD << endl ;
}
}
return 0 ;
}