0

My code is giving the error in first code but second one is running without any error "terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc Aborted (core dumped)" //First

#include<bits/stdc++.h>
using namespace std;
int main()
{
    //code
    int t;
    cin>>t;
    while(t--)
    {
        int n;
        cin>>n;
        string res;
        while(n)
        {
            res.push_back((n%26)  + 'A');
            n=n/26;
            n-=1;
        }
        reverse(res.begin(),res.end());
        cout<<res<<endl;
    }
    return 0;
}

The second code is as follow which is showing no error can anyone tell me why this error is there

while(n)
{
    n-=1;
    res.push_back((n%26)  + 'A');
    n=n/26;
}
  • 1
    What if `n=n/26` ever equals 0? In the first case, `n-=1` will yield a negative value. – François Andrieux May 29 '18 at 19:04
  • Unrelated: Avoid using any includes from `bits`. They are internal headers intended for use only by the library implementation. This particular header, stdc++.h, can be a particularly bad no-no. More on that here: [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) – user4581301 May 29 '18 at 19:06

1 Answers1

0

The problem in the first example is that

while(n)
{
    res.push_back((n%26)  + 'A');
    n=n/26;
    n-=1;
}

will become an infinite loop. Why? Because n/26 is integer division. This means that when n < 26 && n > -26 the division will return 0. As you subtract one at the end of the loop, what will happen is that n will always be -1: -1/26 = 0 and 0 - 1 = -1. Therefore, your string will become too big, and that is what is causing the std::bad_alloc.

The second version works just fine because you subtract one before dividing by 26, which means there will be a point when the loop begins with n=0

aPlutonicCoder
  • 116
  • 1
  • 11