FZU 1752 A^B mod C(快速加、快速幂)

题目链接: 传送门

A^B mod C

Time Limit: 1000MS     Memory Limit: 65536K

思路

快速加和快速幂同时运用,在快速加的时候由于取模耗费不少时间TLE了,最后又进行了改写。

#include<stdio.h>
typedef __int64 LL;


LL mod_mulit(LL x, LL y,LL mod)
{
	LL res = 0;
	while (y)
	{
		if (y & 1)
		{
			res += x;
			while (res >= mod)
			{
				res -= mod;
			}
			//res = (res + x) % mod;  //取模运算耗费时间 
		}
		x += x;
		while (x >= mod)
		{
			x -= mod;
		}
		//x = (x + x) % mod;
		y >>= 1;
	}
	return res;
}

LL mod_pow(LL x,LL n,LL mod)
{
	LL res = 1;
	while (n > 0)
	{
		if (n & 1)
		{
			res = mod_mulit(res, x, mod);
		}
		x = mod_mulit(x,x,mod);
		n >>= 1;
	}
	return res;
}

int main()
{
	LL A,B,C;
	while (~scanf("%I64d %I64d %I64d",&A,&B,&C))
	{
		/*LL res = 1;
		while (B > 0)
		{
			if (B & 1)
			{
				res = mod_mulit(res,A,C);
			}
			A = mod_mulit(A,A,C);
			B >>= 1;
		}*/
		LL sum = mod_pow(A,B,C);
		printf("%I64d\n",sum);
	}
	return 0;
}
posted @   zxzhang  阅读(155)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示

目录导航