Xinlv wrote some sequences on the paper a long time ago, they might be arithmetic or geometric sequences. The numbers are not very clear now, and only the first three numbers of each sequence are recognizable. Xinlv wants to know some numbers in these sequences, and he needs your help.
Input
The first line contains an integer N , indicting that there are N sequences. Each of the following N lines contain four integers. The first three indicating the first three numbers of the sequence, and the last one is K , indicating that we want to know the K -th numbers of the sequence. You can assume 0 < K ≤ 10 9 , and the other three numbers are in the range [0, 2 63 ). All the numbers of the sequences are integers. And the sequences are non-decreasing.Output
Output one line for each test case, that is, the K -th number module(%) 200907 .Sample Input
2 1 2 3 5 1 2 4 5
Sample Output
5 16
快速幂思路(a^b mod n):
可以把b按二进制展开为:b = p(n)*2^n + p(n-1)*2^(n-1) +…+ p(1)*2 + p(0)
其中p(i) (0<=i<=n)为 0 或 1
这样 a^b = a^ (p(n)*2^n + p(n-1)*2^(n-1) +...+ p(1)*2 + p(0))
= a^(p(n)*2^n) * a^(p(n-1)*2^(n-1)) *...* a^(p(1)*2) * a^p(0)
对于p(i)=0的情况, a^(p(i) * 2^(i-1) ) = a^0 = 1,不用处理
我们要考虑的仅仅是p(i)=1的情况
化简:a^(2^i) = a^(2^(i-1) * 2) = ( a^( p(i) * 2^(i-1) ) )^2
(这里很重要!!具体请参阅秦九韶算法: http://baike.baidu.com/view/1431260.htm )利用这一点,我们可以递推地算出所有的a^(2^i)
当然由算法1的结论,我们加上取模运算:
a^(2^i)%c = ( (a^(2^(i-1))%c) * a^(2^(i-1))) %c
于是再把所有满足p(i)=1的a^(2^i)%c按照算法1乘起来再%c就是结果, 即二进制扫描从最高位一直扫描到最低位递归写法://计算a^bmodn int modexp_recursion(int a,int b,int n) { int t = 1; if (b == 0) return 1; if (b == 1) return a%n; t = modexp_recursion(a, b>>1, n); t = t*t % n; if (b&0x1) { t = t*a % n; } return t; }
//本题采用非递归写法 #include <cstdio> #include <iostream> using namespace std; const int mod = 200907; long long modexp(long long a,long long b); int main(){ int n; scanf("%d",&n); while (n--){ long long a,b,c,k; scanf("%lld%lld%lld%lld",&a,&b,&c,&k); if (a + c == b * 2){ cout << (a % mod + (k - 1) % mod * (c - b) % mod) % mod << endl; }else{ cout << a % mod * modexp(b/a,k-1) %mod << endl; } } return 0; } long long modexp(long long a,long long b){ long long res = 1; while (b){ a %= mod; if (b & 1){ res = res * a % mod; //cout << res; } a = a * a % mod; b = b >> 1; //cout << res; } // cout << res; return res; }