您的位置:首页 > 产品设计 > UI/UE

hdu2817 A sequence of numbers && hdu1420 Prepared for New Acmer(快速幂取模)

2016-04-12 09:35 501 查看
http://acm.hdu.edu.cn/showproblem.php?pid=2817

题意:给出一个数列的前三项,求这个数列的第k项。注意体重说过arithmetic or geometric sequences,只可能是等差等比数列中的一种。

首先根据前三项判断是等差还是等比,若等差则直接根据通项公式得出,等比的话数字太大,要用快速幂

快速幂取模,一种神奇的位运算算法。

例如求x的n次方,n很大时要求n次幂,而用位运算转化为二进制后,只有该位为1的才乘一次,复杂度由O(n)转化为O(logn)。至于快速幂的内部实现,其实也很简单,思想上就和dp的二进制一样,任何一个数都可以由2的幂次组成。拿本题说,x用于表示x^2^k,是每个累乘的单向且每次进行左移变化,和n的右移变化同步进行;res用于累乘合法(二进制位为1)的项,相当于幂的累加。通常快速幂都要取一下模,为了防止特别大而溢出。值得一提的是,这题连输入的数都特别大,必须都用LL。

#include <stdio.h>
#include <algorithm>
#include <string.h>

using namespace std;

typedef long long LL;

const int N = 4500;
const int INF = 1e8;
const int mod = 200907;

LL quickmod(LL x, LL n)
{
LL res = 1;
while(n)
{
if(n & 1) res = (res * x) % mod;
n >>= 1;
x = (x * x) % mod;
}
return res;
}

int main()
{
//  freopen("in.txt", "r", stdin);
LL n, a, b, c, num, ans;
scanf("%lld", &n);
while(n --)
{
scanf("%lld%lld%lld%lld", &a, &b, &c, &num);
if(a + c == b * 2) ans = (a + (num - 1) * (b - a)) % mod;
else
{
ans = a * quickmod((b / a), (num - 1)) % mod;
}
printf("%d\n", ans);
}
return 0;
}


http://acm.hdu.edu.cn/showproblem.php?pid=1420

题意:求A^B mod C

和上题想必,这题就逊色很多了

#include <stdio.h>
#include <algorithm>
#include <string.h>

using namespace std;

typedef long long LL;

const int N = 4500;
const int INF = 1e8;
//const int mod = 200907;

LL quickmod(LL x, LL n, LL mod)
{
LL res = 1;
while(n)
{
if(n & 1) res = (res * x) % mod;
n >>= 1;
x = (x * x) % mod;
}
return res;
}

int main()
{
//  freopen("in.txt", "r", stdin);
LL n, a, b, c, ans;
scanf("%lld", &n);
while(n --)
{
scanf("%lld%lld%lld", &a, &b, &c);
ans = quickmod(a, b, c);
printf("%d\n", ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  hdu