Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading