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

模板—慢速乘

时间:2019-07-15 09:18:26      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:strong   define   超过   include   using   cout   ret   amp   main   

用于模数很大直接乘会爆longlong的情况。

#include<iostream>
#include<cstring>
#include<cstdio>
#define LL long long
using namespace std;
LL a,b,p;
LL mull(LL a,LL b,LL p)
{
	LL res=0;
	while(b)
	{
		if(b&1)res=(res+a)%p;
		a=(a+a)%p;
		b=b>>1;
	}
	return res;
}
signed main()
{
	cin>>a>>b>>p;
	LL ans=mull(a,b,p);
	cout<<ans<<endl;
}

好处是只要a,b在long long内,无论它们乘起来多大,都可以做。

劣势是时间复杂度是log(b)的,比起正常乘法来太慢了。

其实有O(1)的方法, 只适用于a*b没有超过long long太多的情况(即a,b并不算大,大概均在10^12左右)

设一个常数t。

令x1=a/t,x2=a%t

    y1=b/t,y2=b%t

显然a*b=(x1*t+x2)*(y1*t+y2)=x1*y1*t*t+x1*y2*t+x2*y1*t+x2*y2。但是感觉并不如慢速乘好用……

模板—慢速乘

标签:strong   define   超过   include   using   cout   ret   amp   main   

原文地址:https://www.cnblogs.com/Al-Ca/p/11186793.html

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