1. 程式人生 > >poj1012:約瑟夫問題

poj1012:約瑟夫問題

import java.util.Scanner;

public class Main {
	static int[] Result = new int[13];

	public static void main(String[] args)  {
		Scanner in = new Scanner(System.in);
		while (in.hasNext()) {
			int K = in.nextInt();
			if (K == 0) {
				return;
			}
			// 沒有這個if,會超時
			if (Result[K - 1] != 0) {
				System.out.println(Result[K - 1]);
				continue;
			}
			getminM(K);
			System.out.println(Result[K - 1]);
		}

	}

	// 測試M是否符合
	public static void getminM(int K) {
		int M;
		// M沒有上限,初始的M值至少為K+1,否則會不符合要求
		for (M = K + 1;; M++) {
			if (test(K, M)) {
				Result[K - 1] = M;
				break;
			}
		}
	}

	// 打表
	//如果
	public static boolean test(int K, int M) {
		boolean isFlag = true;
		int i, t = 0;
		// temp為當前環中的總人數
		int temp = 2 * K;
		for (i = 1; i <= K; i++) {
			// 公式
			t = (t + M - 1) % temp;
			// 環中的人數減少1
			temp--;
			if (t < K) {
				// 如果說初出局的編號在前K個,此時M不符合要求
				isFlag = false;
				return isFlag;
			}
		}
		return isFlag;
	}

}