Algorithm
You are given two integers l and r, l≤r. Find the largest possible value of amodb over all pairs (a,b) of integers for which r≥a≥b≥l.
As a reminder, amodb is a remainder we get when dividing a by b. For example, 26mod8=2.
Each test contains multiple test cases.
The first line contains one positive integer t (1≤t≤104), denoting the number of test cases. Description of the test cases follows.
The only line of each test case contains two integers l, r (1≤l≤r≤109).
For every test case, output the largest possible value of amodb over all pairs (a,b) of integers for which r≥a≥b≥l.
4 1 1 999999999 1000000000 8 26 1 999999999
0 1 12 499999999
In the first test case, the only allowed pair is (a,b)=(1,1), for which amodb=1mod1=0.
In the second test case, the optimal choice is pair (a,b)=(1000000000,999999999), for which amodb=1.
Code Examples
#1 Code Example with C++ Programming
Code -
C++ Programming
#include<bits/stdc++.h>
using namespace std;
#define endl '\n'
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin>>t;
int l, r;
while(t--){
cin>>l;
cin>>r;
if(r/2 < l){
cout<<(r%l)<<endl;
}
else{
cout<<(r%((r/2)+1))<<endl;
}
}
return 0;
}
Copy The Code &
Try With Live Editor
Input
1 1
999999999 1000000000
8 26
1 999999999
Output
1
12
499999999
Demonstration
Codeforcess Solution 1562-A A. The Miracle and the Sleeper ,C++, Java, Js and Python ,1562-A,Codeforcess Solution