码迷,mamicode.com
首页 > 其他好文 > 详细

NYOJ 640 Geometric Sum

时间:2014-05-06 15:20:32      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:nyoj 640 geometric s

Geometric Sum

时间限制:1000 ms  |  内存限制:65535 KB
难度:3
描述
Compute (a + a^2 + … + a^n) mod m.
输入
Three integers a,n,m.
(1≤a,n,m≤10^18)
It ends with EOF.
输出
The only integer denotes the result.
样例输入
2 2 1000000000
样例输出
6 
别人的AC码:
 
#include <stdio.h>
typedef long long LL;
LL Mod;
LL multMod(LL a,LL b)
{
    LL res = 0,base = a;
    while(b)
    {
        if(b&1)
            (res += base) %= Mod;
        (base <<= 1) %= Mod;
        b >>= 1;
    }
    return res;
}

LL powerMod(LL a,LL n)
{
    LL res = 1 , base = a;
    while(n)
    {
        if(n&1)
            res = multMod(res,base);
        base = multMod(base,base);
        n >>= 1;
    }
    return res;
}

LL solve(LL a,LL n)
{
    if(n == 1)
        return a;
    LL halfsum = solve(a,n >>1);
    if(n&1)
    {
        LL half = powerMod(a,n+1 >>1);
        return (halfsum + half + multMod(half,halfsum)) % Mod;
    }
    else
    {
        LL half = powerMod(a,n >>1);
        return (halfsum + multMod(half,halfsum)) % Mod;
    }
}

int main()
{
    LL a,n;
    while(~scanf("%lld%lld%lld",&a,&n,&Mod)){
    a %= Mod;
    printf("%lld\n",solve(a,n));
    }
	return 0;
}
        

NYOJ 640 Geometric Sum,布布扣,bubuko.com

NYOJ 640 Geometric Sum

标签:nyoj 640 geometric s

原文地址:http://blog.csdn.net/u012804490/article/details/25039221

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!