算阶第一章64位整数乘法

龟速乘

题目描述

求 a 乘 b 对 p 取模的值,其中 1≤a,b,p≤10^18

输入和输出

Input

第一行a,第二行b,第三行p。

Output

一个整数,表示a*b mod p的值。


首先只是64位整数乘法,而且会取模,所以不需要写高精。

#include <bits/stdc++.h>
using namespace std;
unsigned long long a,ans,b,q;
int main()
{
    
    
	cin>>a>>b>>q;
	while(a)
	{
    
    
		ans+=((a%10)*b%q)%q;
		ans%=q;
		b=b*10%q;
		a/=10;
		
	}
	cout<<ans;
	return 0;
}

这个比书上的好像快一点,用数学方法可推。

猜你喜欢

转载自blog.csdn.net/ydsrwex/article/details/112253076
今日推荐