This page is still under construction.

Parts of this page are still being built. What you see may change.

Josephus Problem 3

Interview

Time limit1sMemory limit16 MB

Summary
Find the number of the last person remaining after removing every K-th of N people seated in a circle.
Level

Medium4 of 10

Topics
Math, Dynamic programming
Solved
No attempts yet

Problem

The Josephus problem is as follows.

NN people numbered 1 to NN sit in a circle, and a positive integer KK (K≤NK \le N) is given. Counting in order, every KK-th person is removed. Once a person is removed, the counting continues around the circle formed by the remaining people. The process runs until all NN people are removed, and the order in which people are removed is the (N,K)(N, K)-Josephus permutation. For example, the (7,3)(7, 3)-Josephus permutation is <3, 6, 2, 7, 5, 1, 4>.

Given NN and KK, write a program that finds the number of the person who remains last.

Input

The first line contains NN and KK in that order, separated by a space. (1≤K≤N≤5,000,0001 \le K \le N \le 5{,}000{,}000)

Output

Print the number of the person who remains last on the first line.

Examples1

  1. Example 1

    Input
    7 3
    
    Expected output
    4