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


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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值