D
D
dmasloff2020-12-20 00:30:41
C++ / C#
dmasloff, 2020-12-20 00:30:41

How to follow the sign of a variable on overflow in C++?

There is a task where you need to follow the sign of a variable in a long long as a result of overflow. The bottom line is that we are given a natural number (it is less than 10 ^ 9), and at each step we multiply the number stored in long long (first it is 1) by this natural number and we need to find at what step the variable will become negative. I tried to implement this using the base 2 logarithm (ceil(63.0/log2(x))), but this way you can only count the number of steps until the type overflows, and for some values ​​of the variable, when overflowing, we again get into positive numbers. I tried to implement a recursive function, but it does not work either. Accordingly, what is the most convenient way to follow this without using direct multiplication inside the while?

#include <iostream>
#include <cmath>

using namespace std;

int f(long long a, int temp) {
  if (a == temp) {
    int ft = ceil(63.0 / log2(temp));
    if ((long long)pow(temp, ft) <= 0) {
      return ft + 1;
    }
    else {
      return ft + f(pow(temp, ft), temp);
    }
  }
  else {
    int ft = ceil((63.0 - log2(a)) / log2(temp));
    if ((long long)a * pow(temp, ft) <= 0) {
      return ft + 1;
    }
    else {
      return ft + f(a * pow(temp, ft), temp);
    }
  }
}

int main() {
  long long a, temp;
  cin >> a;
  temp = a;
  cout << f(a, temp);
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
X
xorknown, 2020-12-20
@xorknown

You have the wrong approach. If you take an abstract machine, then you can not follow the sign of the variable, since the standard does not guarantee that it will change. You really can't overfill.
You need to define this before the overflow. The dumbest way is to subtract one of the arguments from the maximum number and compare the resulting number with the second argument (if the resulting number is less, then it means overflow).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question