My issue
This code is working fine, but in the else condition, why it is giving wrong answer when I write (ceil(diff/2.0) + 1) instead of (diff/2 + 2) ?? The logic is same, then why answer is wrong? Please explain me with some example test case or something.
My code
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin>>t;
while(t--){
int x,y;
cin>>x>>y;
int diff = x - y;
if(diff <= 0){
cout<<y - x<<endl;
}
else if(diff % 2 == 0){
cout<<diff/2<<endl;
}
else{
cout<<diff/2 + 2<<endl;
}
}
return 0;
}
Problem Link: INCREAR Problem - CodeChef
@smeet8267 Just take long int instead of int u can get integer overflow error .
@dpcoder_007 I used Long here, still getting wrong answer for the last test case. Kindly review it.
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin>>t;
while(t--){
long x,y;
cin>>x>>y;
long diff = x - y;
if(diff <= 0){
cout<<y - x<<endl;
}
else{
cout<<ceil(diff/2.0) + diff%2<<endl;
}
}
return 0;
}
@smeet8267
Just do it like this to avoid overflow.
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin>>t;
while(t--){
long int x,y;
cin>>x>>y;
long int diff = x - y;
if(diff <= 0){
cout<<y - x<<endl;
}
else{
long int ans=ceil(diff*1.0/2.0) + diff%2;
cout<<ans<<endl;
}
}
return 0;
}
You used 2.0(which is floating point number)
If you use 2 which is an integer then all test cases may pass