0

I was given this problem which gives you 2 integers n and m, n representing the number of figures of the second number, and the second number is a binary number. For example:

n= 2          
m= 11  

After figuring out the binary number, you have to get that number to be 0. You are only allowed to substract 1 from the binary or divide by two. For example, in this case it would be:

3->2->1   so the result is 2 since  there were 2 operations made

My program does work and displays the binary number and the number of operations. But when given big numbers, it throws floating point exception. My theory is that it is because ints are too short. But when I change them to longs, it throws a completely inaccurate result.

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int n, m, g, l, f, x, k, w;
    cin >> n >> m;
    g = pow(10, n);
    k = pow(2, n - 1);
    for (int i = 1; i <= n; i++)
    {
        l = m % g;
        f = l / (g / 10);
        if (f == 1)
        {
            x += k;
        }
        k /= 2;
        g /= 10;
    }
    cout << x << endl;
    while (x != 1)
    {
        if (x % 2 == 0)
        {
            x /= 2;
        }
        else
        {
            x -= 1;
        }
        w++;
    }
    cout << w;
    return 0;
}
Christophe
  • 68,716
  • 7
  • 72
  • 138
rodrigo
  • 9
  • 1
  • 1
    1) `#include ` -- Use the proper headers. This is not one of them. 2) If you know what the input is, then assign that input directly into the variables. There is no need for `cin`. 3) The formatting of the code is not good. It is very hard to read. – PaulMcKenzie Jan 10 '20 at 19:20
  • 1
    1) Please provide sample input, where your execution provides described issues. 2) In `f=l/(g/10);`, if `g < 10 && g >-10` - you will divide `l` by zero, which will result in undefined behavior. – Algirdas Preidžius Jan 10 '20 at 19:21
  • 3
    `x` and `w` are not initialized. A good compiler would have [warned you](http://coliru.stacked-crooked.com/a/4f5242bba951185a) – PaulMcKenzie Jan 10 '20 at 19:25
  • 2
    `pow` on integers is risky. `pow` operates on floating point numbers and the best a floating point number can guarantee is "Close enough." This can have catastrophic results when converted back to an integer. See [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) and its linked documents for more. – user4581301 Jan 10 '20 at 19:44
  • Indeed: intialize x and w and it will work. Demo: https://ideone.com/gG4BqA – Christophe Jan 10 '20 at 19:59

0 Answers0