Different values for integer

Trying to insert values of square and cube of a number in set st and st1. (Let n = 10^7).
After printing, set st is having negative values due to limit of integer but there are no negative values in set st1 even though both ‘i’ and ‘temp’ are integers.

        int n;
        cin >> n;
        int temp = 2;
        set<int> st;
        set<int> st1;

        while ((temp * temp) < n)
        {
            st.insert(temp * temp);
            if ((temp * temp * temp) < n)
            {
                st.insert(temp * temp * temp);
            }
            temp++;
        }

        for(int i=1;i*i<n;i++){
            st1.insert(i * i);
        }
        for(int i=1;i*i*i<n;i++){
            st1.insert(i* i * i);
        }

        for(auto ss : st){
            cout<<ss<<" ";
        }

        cout<<"\n\n";

        for(auto s : st1){
            cout<<s<<" ";
        }

    }

>Solution :

The behaviour of temp * temp < n is undefined if temp * temp overflows the type. Wraparound to negative is commonly observed but even with architectures that do that, optimising compilers are permitted to assume that if a + c < b + c for a constant c then a < b.

temp < n / temp is a common refactoring that does not suffer from that overflow. You do of course need to check for non-zero temp.

Leave a Reply