Home c++ How to raise 2 to power i without pow

How to raise 2 to power i without pow

Author

Date

Category

How to raise 2 to the power i. Forbidden to use pow


Answer 1, authority 100%

I think if the author of the question meant the integer i, and not too large, then this is usually done in one operation

result = 1 << i;

However, here you need to do a lot of all kinds of checks, depending on the specific task. For example, if the expected result is greater than the bit depth of the typical data types of the programming language allows. If we are talking about large i, then long arithmetic should be used.

If iis fractional, then traditionally several techniques are used for this: reduction of the argument and the subsequent Newton method. There are other options, but it seems to me that the author of the question does not need this.


Answer 2

#include<iostream>
using namespace std;
int main()
{
    setlocale(LC_ALL, "rus");
    int x = 2; //Number
    int y = 4; //Degree
    int out = x;
    for (int i = 1; i < y; i++)
    {
        out = out * x;
    }
    cout <<"ANSWER: " << out << endl;
    system("pause");
}

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions