3n + 1 Problem

UVA 100

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		while (sc.hasNext()) {
			int i = sc.nextInt();
			int j = sc.nextInt();
			int mark = -1;
			if (i > j) {
				int temp = i;
				i = j;
				j = temp;
				mark = 1;
			}
			int maxLen = f(i);
			for (int index = i; index <= j; index++) {
				int curLen = f(index);
				if (curLen > maxLen) {
					maxLen = curLen;
				}
			}
			if (mark == -1) {
				System.out.println(i + " " + j + " " + maxLen);
			} else {
				System.out.println(j + " " + i + " " + maxLen);
			}
		}
	}

	// 返回n的循环节长度
	private static int f(int n) {
		if (n == 1) {
			return 1;
		}
		if (n % 2 == 0) {
			return 1 + f(n / 2);
		} else {
			return 1 + f(3 * n + 1);
		}
	}

}

猜你喜欢

转载自blog.csdn.net/a739260008/article/details/86443989
今日推荐