HDU 5666 Segment(快速乘)

题目链接:点击这里
在这里插入图片描述
当数非常大时,计算 (a*b)%m 使用 long long 也有可能爆精度,此时需要转乘法为加法,在模拟的同时不断求模。

#include<iostream>
#include<algorithm>
#include<string>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<stack>
#include<queue>

using namespace std;
typedef long long ll;
const int MOD = 10000007;
const int INF = 0x3f3f3f3f;
const double PI = acos(-1.0);
const int maxn = 1010;

ll mult_mod(ll a, ll b, ll m)
{
    ll res = 0;
    while(b)
    {
        if(b&1)
           res = (res+a)%m;
        a = (a+a)%m;
        b >>= 1;
    }
    return res;
}

int main()
{
	int t;
	ll q, p;
	scanf("%d", &t);
	while(t--)
	{
		scanf("%lld%lld", &q, &p);
		if(q&1)	printf("%lld\n", mult_mod((q-1)/2, q-2, p));
		else	printf("%lld\n", mult_mod(q-1, (q-2)/2, p));
	}
	
	return 0;
}
发布了673 篇原创文章 · 获赞 103 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/qq_42815188/article/details/104045451
今日推荐