[CSP-J 2022 T1] 乘方

作者: qiqi 分类: CSP-J 发布时间: 2025-10-06 12:03

查看题目

#include <bits/stdc++.h>
using namespace std;

int main()
{
	long long res = 1;
	int a, b;
	cin >> a >> b;

	res = a;
	if (a != 1 && b != 1)
	{
		for (int i = 0; i < b - 1; i++)
		{
			res *= a;
			if (res > 1e9)
			{
				res = -1;
				break;
			}
		}
	}

	cout << res << endl;
	return 0;
}

通过计算a的值应该是小于等于31622的,不然平方就会大于1E9.
同理,b是小于等于29的,否则2的b次方就会大于1E9。
所以可以加入下面的判断:

if(a > 31622)
{
    cout << -1 << endl;
    return 0;
}
if(b > 29)
{
    cout << -1 << endl;
    return 0;
}

更为简介的做法是,使用pow函数:

#include <bits/stdc++.h>
using namespace std;

int main()
{
    int a, b;
    cin >> a >> b;
    double x = pow(a, b);
    cout << int(x > 1e9 ? -1 : x) << endl;
    return 0;
}

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

标签云