This page is still under construction.

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

Double Dealing

Time limit15sMemory limit32 MB

Summary
Simulate dealing and gathering the deck to find the number of repetitions after which the card order returns to the start.
Level

Medium7 of 10

Topics
Simulation, Math, Number theory
Solved
No attempts yet

Problem

You are given a deck of nn distinct cards. Deal the entire deck to kk players in the usual way: the top card goes to player 1, the next to player 2, the kk-th to player kk, the (k+1)(k+1)-th back to player 1, and so on until the deck runs out.

Then gather the cards back up. Place player 1's pile on top, player 2's pile beneath it, and so on, so that player kk's pile ends up on the bottom. Within each player's pile the cards are in reverse order of dealing: the last card that player was dealt is on top, and the first is on the bottom.

Counting the first deal, how many times must this whole process be repeated before the deck returns to its original order?

Input

The input contains multiple test cases. Each case is a single line with two integers nn and kk (1≤n≤8001 \le n \le 800, 1≤k≤8001 \le k \le 800). The input ends with a line containing two zeros.

Output

For each test case, print a single integer: the number of deals needed to return the deck to its original order. Print each integer on its own line, with no extra spaces and no blank lines between answers. For every possible input the answer fits in a signed 64-bit integer.

Examples1

  1. Example 1

    Input
    1 3
    10 3
    52 4
    0 0
    
    Expected output
    1
    4
    13