zoj3549 快速幂

题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3549

一般算a^b是用这种方法

int pow( int a, int b )
{
    int r = 1;
    while( b-- )
	r *= a;
    return r;
}

时间复杂度为O(n)。
当b比较大时就不行了,需要使用快速幂方法,其实就是二分时间复杂度为O(logn)。
具体看例子如:5^7,c=1;
7=(111),每次7右移一位,c=c*5。如下表:

b

7

3

1

0

c

1

5^1

5^1*5^2

5^1*5^2*5^4


AC源代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#define LL long long
using namespace std;
const long long con=1000000000;

LL QuickM (LL a,LL b)//快速幂
{
  if (a==0)
	return 1;
  LL num=1;
  a=a%con;//都要取个模,不然会出错
  while (b)
	{
	  if (b%2)
		num=(num*a)%con;//取模
	  a=(a*a)%con;//取模
	  b>>=1;
	}
  return num;
}
int main ()
{
  LL m,n,i,j;
  while (scanf ("%lld%lld",&m,&n)!=EOF)
	{
	  LL sum=0,num=0;
	  for (i=1;i<=m;i++)
		{
		  sum+=QuickM (i,n);
		  //sum=sum%con;
		}
	  while (1)
		{
		  if (sum%10!=0)
			break;
		  num++;
		  sum/=10;
		}
	  printf ("%lld\n",num);
	}
  return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值