小浩的幂次运算(快速幂)

传送门

看到该题庞大的数据量以及幂运算,很明显,我们需要使用快速幂解决

然后对于该,我们可以对两边同时取对数,这样就可以得到对应的指数是多少,这里可以利用cmath库函数log()进行对数计算,只需进行简单的对数转换即可,例如log(8)/log(2)=log2(8)=3

值得注意的是因为这里利用了除法,因此还需要注意分母为0的情况

#include<iostream>
#include<cmath>
#define LL long long//开long long

using namespace std;

LL fun(LL a,LL b){//快速幂模板
	LL ans=1,temp,base,index;
	temp=a;
	base=a;
	index=b;
	while(b>0){
		if(b&1){
			ans=ans*temp;
		}
		temp=temp*temp;
		b>>=1;
	}
//	cout<<base<<"^"<<index<<"="<<ans<<endl;
	return ans;
}

signed main(){
	LL L,R,W,i=0,count=0;
	cin>>L>>R>>W;
	if(W==1){//特判分母为0的情况(因为log(1)=0)
		if(1>=L&&1<=R){
			cout<<1<<endl;
		}else{
			cout<<-1<<endl;
		}
		return 0;
	}
	LL index1=log(L)/log(W);//对数转换
	LL index2=log(R)/log(W);
	for(int i=index1;i<=index2;i++){
		LL res=fun(W,i);//得到对应数字
		if(!(res>=L&&res<=R)){//是否符合
			continue;
		}
		if(count==0){
			cout<<res;
		}else{
			cout<<" "<<res;
		}
		count++;
	}
	if(count==0){//一个都没输出就输出-1
		cout<<-1;
	}
	cout<<endl;
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZZZWWWFFF_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值