'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 1:[1]
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
.
Solution 2:[2]
Your for loop stops once the first cube reaches 10^7. But your while loop continues until the first sqare reaches 10^7. At this point (n=3163) the cube already exceeded INT_MAX.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Bathsheba |
Solution 2 | MattTT |