import java.io.*; import java.util.*; /** * Double Dealing * @author vanb * * The numbers here are too big to simulate. So, build a graph, * where every node is a position in the deck. Each node has a * single link, which goes to the position in the deck where that card * would go after one deal/pickup. Then, take the Least Common Multiple * of the lengths of all of the cycles. */ public class doubledealing { public Scanner sc; public PrintStream ps; /** * Greatest Common Factor, by Euler's method * * @param a A number * @param b Another number * @return The GCF of a and b */ long gcf( long a, long b ) { return b==0 ? a : gcf( b, a%b ); } /** * Least Common Multiple * * @param a A number * @param b Another number * @return The LCM of a and b */ long lcm( long a, long b ) { return a / gcf(a,b) * b; } /** * Do it! * * @throws Exception */ public void doit() throws Exception { sc = new Scanner( System.in ); //new File( "doubledealing.in" ) ); ps = System.out; //new PrintStream( new FileOutputStream( "doubledealing.out" ) ); int deck[] = new int[1000]; for(;;) { int n = sc.nextInt(); int m = sc.nextInt(); if( n==0 ) break; // This is the highest card held by player 0. int highcard = n - n%m; // Figure out where every card goes after 1 deal/pickup // k is a position in the deck int k=0; // Go through by player, since all of a player's cards // will be together when they get picked up. for( int i=0; i=n ) card -= m; // Place all of player i's cards while( card>=0 ) { deck[k++] = card; // All of a player's cards have // the same remainder mod m card -= m; } } // Think of the deck as links in a graph. // A cycle of length n means that after n deals/pickups, // all the cards in the cycle are back in their original positions. // So, we've just got to find all of the cycles, and take the // Least Common Multiple of all of their lengths. long result = 1l; for( int i=0; i=0 ) { long count = 0; int card = i; while( deck[card]>=0 ) { ++count; int savecard = card; card = deck[card]; // Mark this node as 'visited' deck[savecard] = -1; } result = lcm( result, count ); } ps.println( result ); } } /** * Main * @param args Unused * @throws Exception */ public static void main( String[] args ) throws Exception { new doubledealing().doit(); } }