一本通2086【22CSPJ普及组】乘方(pow)的题解

先看题。

题目

很明显,这是一道水题。

题解:

萌新写,会直接写成这样:

#include<bits/stdc++.h>
using namespace std;
int a,b;
int main(){
    cin>>a>>b;
    long long s=a;
    for(int i=1;i<=b-1;i++){
        s*=a;
    }
    if(s>1000000000) cout<<"-1";
    else cout<<s;
    return 0;
}

这很明显不行对吧,看结果

其实我也想不出咋了,于是我添了点油,加了点醋。

首先我们算出十的九次方的算术平方根:

#include<bits/stdc++.h>
using namespace std;
int main(){
    double s=sqrt(1000000000);
    printf("%.37lf",s);
    return 0;
}

然后得出答案:

得出31622.7766016837922506965696811676025390625,因为输入都是整数,所以取31622就行了,然后写出代码:


#include<bits/stdc++.h>
using namespace std;
int a,b;
int main(){
    cin>>a>>b;
    if(a>31622){
        cout<<"-1";
        return 0;
    }
    long long s=a;
    for(int i=1;i<=b-1;i++){
        s*=a;
    }
    if(s>1000000000) cout<<"-1";
    else cout<<s;
    return 0;
}

当然,我还得添点油加点醋。

我们要求出2ⁿ<=1000000000<=2ⁿ⁺1中n的值。

代码省略,得出29。

所以代码变成:

#include<bits/stdc++.h>
using namespace std;
int a,b;
int main(){
    cin>>a>>b;
    if(a>31622){
        cout<<"-1";
        return 0;
    }
    if(b>29){
        cout<<"-1";
        return 0;
    }
    long long s=a;
    for(int i=1;i<=b-1;i++){
        s*=a;
    }
    if(s>1000000000) cout<<"-1";
    else cout<<s;
    return 0;
}

等等!还没完!再加上

if(b==1){
    cout<<a;
    return 0;
}

if(a==1){
    cout<<1;
    return 0;
}

最终AC代码

#include<bits/stdc++.h>
using namespace std;
int a,b;
int main(){
    
    cin>>a>>b;
    if(a==1){
        cout<<1;
        return 0;
    }
    if(b==1){
        cout<<a;
        return 0;
    }
    if(a>31622){
        cout<<"-1";
        return 0;
    }
    if(b>29){
        cout<<"-1";
        return 0;
    }
    long long s=a;
    for(int i=1;i<=b-1;i++){
        s*=a;
    }
    if(s>1000000000) cout<<"-1";
    else cout<<s;
    return 0;
}

结果

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值