您的位置:首页 > 其它

九度OJ 1442/HDU 2817 (二分求幂)

2018-01-10 14:17 369 查看


题目描述

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.


输入描述:

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 one line for each test case, that is, the K-th number module (%) 200907.


分析:数值的范围很大,并且要取模,所以这里主要运用二分求幂,及取模公式

       ①(a*b)%c=((a%c)*(b%c))%c

  ②(a+b)%c=((a%c)+(b%c))%c

一开始一直WA的原因在于 判断等比数列时不能直接用if(x3/x2=x2/x1),因为有可能是1 0 0 0 0 这样的等比

所以 判断等比只能用等差的判断条件的else

代码如下:

#include <stdio.h>
long long GetK1(long long s,long long p,long long k)
{
long long ans;
k=k-1;
ans=(s%200907+(p%200907)*(k%200907)%200907)%200907;
return ans;
}
long long GetK2(long long s,long long q,long long k){
k=k-1;
long long ans=1;
while(k!=0){
if(k%2==1){
ans*=q;
ans=ans%200907;
}

q*=q;
k/=2;
q=q%200907;

}
return ((s%200907)*(ans%200907))%200907;

}

int main(int argc, char** argv) {
int N;
while(scanf("%d",&N)!=EOF)
{
while(N--){
long long x1,x2,x3;
long long k;
long long ans;
scanf("%lld%lld%lld%lld",&x1,&x2,&x3,&k);
int flag;
if(x2-x1==x3-x2) flag=0;
else flag =1;
if(flag==0) {
long long p=x2-x1;
ans =GetK1(x1,p,k);
}
else{
long long q=x2/x1;
ans=GetK2(x1,q,k);
}

printf("%lld\n",ans);
}
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: