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

题目描述

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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值