LearnToCP
Sign in
Navigation
HomeRoadmapProblemsAbout Us
Theory
Contest Knowledge
Selecting an IDE
Basics
Your First ProgramData types and IOC++ syntaxModuloFunctionsVectorsMatricesTime Complexity
Sorting
SortingCounting sortRadix Sort
Optimization Techniques
Two PointersSum of numbers 1 to nPrefix sumBinary SearchGreedyBinary Search FunctionsBinary Search by AnswerDivide and Conquer
Binary Numbers
Binary NumbersNumbers in codeBitwise OperationsBitmasks
Math
Binary ExponentiationPrime NumbersPrime FactorizationGCD and LCMSieve of EratosthenesModified Sieve
Data Structures
StringsStackQueueMapsSetsPriority QueueCustom Criteria for FunctionsSegment TreesFenwick TreesSparse TablesUnion Find
Combinatorics
Addition PrincipleMultiplication PrincipleCombinatoric ObjectsInclusion Exclusion Principle
Geometry
Geometry BasicsVectorsCross and Dot ProductLinesPolygonsAnglesPoint in PolygonDistances and Intersection PointsConvex HullCircles
Recursion
PointersRecursionGenerating Combinatoric Objects
Dynamic Programming
About DPTree DPBitmask DPDigit DP
Graph Theory
GraphsDFS and BFSShortest PathsTreesTopological SortingDijkstra's AlgorithmMinimum Spanning TreesShortest Path Algorithms
Advanced Graph Theory
BiconnectivityStrongly Connected ComponentsBipartite GraphGraph FlowAugmenting PathsFlow - Minimum Cut DualityHeavy-Light DecompositionCentroid Decomposition
Advanced Data Structures
2D and 3D Segment TreesLazy PropagationImplicit Segment TreesPersistent Segment TreesLowest Common AncestorTrieBalanced Binary Search TreesMo's Algorithm

Josephus Problem

EasyProblem #27
Time LimitMemoryInputOutput
1 s64 MBstdinstdout

Students numbered 0 to n−1 sit in a circle and play a counting-out game. The counting starts from student 0 and goes around the circle; every m-th student is out of the game, and the counting continues from the next one. Your task is to determine which student remains last.

Input

First line of input will be a single integer t - the number of testcases.
Each of the next t lines contains two integers n and m - the number of students and the length of the count.

Output

For every testcase print a single line with the number of the last remaining student.

Example

Input
2
8 3
2 2
Output
6
0

In the first testcase the students leave in the order 2,5,0,4,1,7,3 and student 6 remains. In the second, counting 0,1 eliminates student 1, so student 0 remains.

Constraints

1≤t≤100
2≤n≤5000
2≤m≤n
n1​+n2​+…+nt​≤5000


This problem was adapted, with permission, from Josifov problem, authored by Društvo matematičara Srbije and Fondacija Petlja.

Submit your solution

Sign in to submit your solution and track your progress.

Sign in to submit