#include #include #include using namespace std; long long gcd(long long a, long long b) { return a ? gcd(b % a, a) : b; } int A[1010]; bool vis[1010]; int main() { int N, K; for(cin >> N >> K; N || K; cin >> N >> K) { /* Compute the permutation induced by the shuffle. */ int M = 0; for(int i = 0; i < K && i < N; i++) { for(int j = (N - i - 1) / K * K + i; j >= 0; j -= K) { A[M++] = j; } } /* Compute the lcm of the cycle lengths of the permutation. */ long long res = 1; memset(vis, 0, sizeof(vis)); for(int i = 0; i < N; i++) { int x = i; int ln = 0; while(!vis[x]) { vis[x] = true; x = A[x]; ln++; } /* Careful to divide then multiply here. */ if(ln) res = res / gcd(res, ln) * ln; } cout << res << endl; } }