Save the Princess

Problem

The only daughter Princess of the neighboring country of the information kingdom has been captured by a monster in the forest.
There are N princes in the information kingdom, and they both agree to go rescue the princess. The king of the information kingdom decides which prince to go to rescue the princess in the following way.

The king numbered the princes in order of age, from 1 to N. Then, from Prince 1 to Prince N, take turns clockwise and have them sit in a circle. Then, starting with Prince 1, they turn clockwise, starting with 1, and have them shout the number. When a prince shouts K (a certain number), the prince is excluded from going to rescue the princess and comes out of the circle. Then, starting with the next prince, the number is called again, starting with 1.

In this way, the last remaining prince can go to rescue the princess.


crane1


For example, suppose there are a total of 8 princes, and the prince who shouted 3 is excluded. At first, Prince 3 shouts 3 and is excluded. Then, Princes 6, 1, 5, 2, 8, and 4 are excluded in turn, and Prince 7, who remains until the end, goes to rescue the princess.
Write a program that, given N and K, prints the number of the prince who will go to rescue the princess.

input

The first line gives the natural numbers N(5<=N<=1,000) and K(2<=K<=9).

8 3

output

Prints the number of the last remaining prince on the first line.

7

Solution

using queue

function solution(n, k) {
	let answer;
	let queue = Array.from({ length: n }, (v, i) => (v = i + 1));

	while (queue.length) {
		for (let i = 1; i < k; i++) queue.push(queue.shift());
		queue.shift();
		if (queue.length === 1) answer = queue.shift();
	}

	return answer;
}