A sequence of numbers(快速幂)

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

分析:先判定数列是等差还是等比数列,然后求出第k项的值。在等比数列中数值可能会超过long long 范围,因此采用快速幂求解。

#include <iostream>
#include <cmath>
typedef long long ll;
using namespace std;
ll app(ll a,ll b)
{
    
    
    ll ans=1;
    while(b)///快速幂:==b个a相乘;
    {
    
    
        if(b&1)///等价于b是奇数;
            ans=(a*ans)%200907;
        b/=2;
        a=(a*a)%200907;
    }
    return ans;
}
int main()
{
    
    
    ll T,a,b,c,k;
    cin>>T;
    while(T--)
    {
    
    
        cin>>a>>b>>c>>k;
        if(2*b==a+c)
        {
    
    
            ll p=(a+(b-a)*(k-1))%200907;
            cout<<p<<endl;
        }
        else
        {
    
    
            ll p;
            p=(((app(b/a,k-1)%200907)*(a%200907))%200907);///为避免超出ll范围;
            cout<<p<<endl;

        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/cuijunrongaa/article/details/106037466