4136: 乘方 [CSP-J 2022]

内存限制:128 MB 时间限制:1.000 S
评测方式:文本比较 命题人:
提交:9 解决:6

题目描述

小文同学刚刚接触了信息学竞赛,有一天她遇到了这样一个题:给定正整数 lns="http://www.w3.org/1998/Math/MathML"> 和 lns="http://www.w3.org/1998/Math/MathML">,求 lns="http://www.w3.org/1998/Math/MathML"> 的值是多少。

lns="http://www.w3.org/1998/Math/MathML"> 即 lns="http://www.w3.org/1998/Math/MathML"> 个 lns="http://www.w3.org/1998/Math/MathML"> 相乘的值,例如 lns="http://www.w3.org/1998/Math/MathML">23 即为 lns="http://www.w3.org/1998/Math/MathML">3 个 lns="http://www.w3.org/1998/Math/MathML">2 相乘,结果为 lns="http://www.w3.org/1998/Math/MathML">2×2×2=8

“简单!”小文心想,同时很快就写出了一份程序,可是测试时却出现了错误。

小文很快意识到,她的程序里的变量都是 int 类型的。在大多数机器上,int 类型能表示的最大数为 lns="http://www.w3.org/1998/Math/MathML">2311,因此只要计算结果超过这个数,她的程序就会出现错误。

由于小文刚刚学会编程,她担心使用 int 计算会出现问题。因此她希望你在 lns="http://www.w3.org/1998/Math/MathML"> 的值超过 lns="http://www.w3.org/1998/Math/MathML">109 时,输出一个 -1 进行警示,否则就输出正确的 lns="http://www.w3.org/1998/Math/MathML"> 的值。

然而小文还是不知道怎么实现这份程序,因此她想请你帮忙。

输入

输入共一行,两个正整数 lns="http://www.w3.org/1998/Math/MathML">,

输出

输出共一行,如果 lns="http://www.w3.org/1998/Math/MathML"> 的值不超过 lns="http://www.w3.org/1998/Math/MathML">109,则输出 lns="http://www.w3.org/1998/Math/MathML"> 的值,否则输出 -1

样例输入 复制

10 9

样例输出 复制

1000000000

提示

数据范围

对于 lns="http://www.w3.org/1998/Math/MathML">10% 的数据,保证 lns="http://www.w3.org/1998/Math/MathML">=1
对于 lns="http://www.w3.org/1998/Math/MathML">30% 的数据,保证 lns="http://www.w3.org/1998/Math/MathML">2
对于 lns="http://www.w3.org/1998/Math/MathML">60% 的数据,保证 lns="http://www.w3.org/1998/Math/MathML">30lns="http://www.w3.org/1998/Math/MathML">1018
对于 lns="http://www.w3.org/1998/Math/MathML">100% 的数据,保证 lns="http://www.w3.org/1998/Math/MathML">1,109


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

#include<bits/stdc++.h>
using namespace std;
/*方法二:倍增法求快速幂-时间复杂度-O(logn) */
long long quickpow(long long a,long long b) {
	long long ans=1;
	while(1) {
		if (b&1) ans *=a;
		b >>= 1;
		if (b==0) return ans > 1e9?-1:ans;
		a *=a;
		if(a>1e9) return -1;
	}
	return ans;
}
int main(){
    long long a,b;cin>>a>>b;
    cout<<quickpow(a,b)<<endl;
	return 0;
}