CSP-J semi-finals sprint must-do questions | P8813 Power

Learn C++ from a young age! Record the questions in the CSP-J exam preparation study process and record every moment.

Attached is a summary post: CSP-J semi-final sprint must-answer questions | Summary_Blog of a communicator who loves programming-CSDN Blog


[Title description]

Xiaowen had just come into contact with the information science competition. One day she encountered such a question: Given positive integers  a  and  b , find the value of a^b.

a^b is  the value of b multiplied by a  .   For example, 2^3 is the multiplied value of three 2s, and the result is 2×2×2=8.

"Simple!" Xiaowen thought to himself, and quickly wrote a program, but an error occurred during the test.

Xiaowen quickly realized that the variables in her program were all of type int. On most machines, the maximum number that can be represented by the int type is 2^31-1, so her program will error whenever the result exceeds this number.

Since Xiaowen has just learned programming, she is worried that there will be problems using int calculations. Therefore, she hopes that you will output a -1 as a warning when the value of a^b exceeds 10^9, otherwise, output the correct value of a^b.

However, Xiaowen still doesn't know how to implement this program, so she wants to ask you for help.

【enter】

Input a total of one line, two positive integers a, b a , b .

【Output】

The output is in one line. If the value of a^b does not exceed 10^9, the value of a^b is output, otherwise -1 is output.

【Input sample】

10 9

【Output sample】

1000000000

[Detailed code explanation]

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

int main()
{
    long long a, b;
    long long ans = 1;
    cin >> a >> b;
    for (int i=1; i<=b; i++) {
        ans *= a;
        if (ans > 1e9) {
            cout << -1 << endl;
            return 0;
        }
    }
    cout << ans << endl;
    return 0;
}

【operation result】

10 9
1000000000

Guess you like

Origin blog.csdn.net/guolianggsta/article/details/133385392