LL power (int a, int b) {
LL result = 1;
while (b -- ) result = (LL)result * a;
return result;
}
int main ( ) {
typedef long long LL;
int a, b; cin >> a >> b;
LL result = (LL)power (a, b);
cout << (result > 1000000000? -1: result);
}
显然这不是正解,两个问题: \color{blue}显然这不是正解,两个问题: 显然这不是正解,两个问题:
1.时间复杂度
2.109的109次方会爆掉
解决第一个,快速幂可以解决(毕竟109的log才20左右)
LL power (int a, int b) {
LL result = 1;
while (b) {
if (b & 1) result = (LL)result * a;
a = (LL)a * a;
b >>= 1;
}
return result;
}
int main ( ) {
typedef long long LL;
int a, b; cin >> a >> b;
LL result = (LL)power (a, b);
cout << (result > 1000000000? -1: result);
}
可是109的109次方还是会爆掉,所以暴力求ab,在过程中判断。
LL result = 1; for (int i = 1; i <= b; i ++ ) { result = (LL)result * a; if (result > 1000000000) { cout << -1; return 0; } } cout << result;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
试一下极限数据(a=109,b=109):
i=1, result=109
i=2, result=1018, 还没爆掉,1018>109,结束,输出-1
水题拿下。
#include
#define FOR(i, a, b) for(int i = a; i <= b; i ++ )
#define DOR(i, a, b) for(int i = b; i >= a; i -- )
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
int a, b;
LL res = 1;
int main () {
freopen ("pow.in", "r", stdin);
freopen ("pow.out", "w", stdout);
cin >> a >> b;
for (int i =