Project Euler p14 - Longest Collatz sequence

发现一个好玩的站, 没事刷刷题

http://projecteuler.net/problem=14

 

找一百万以内的最大起始数, 一个个数过去就好了, 用上DP, 45ms

 

	@Test
	public void t2() {
		final int R = 1_000_001;
		int[] record = new int[R];
		record[1] = 1;
		long ti;
		int c, maxCount = 0, maxR = 0;
		for (int i = 2; i < R; i++) {
			c = 0;
			ti = i;
			while (ti > i || record[((int) ti)] == 0) {
				if (ti % 2 == 0) ti /= 2;
				else ti = ti * 3 + 1;
				c++;
			}
			c += record[((int) ti)];
			record[i] = c;

			if (c > maxCount) {
				maxCount = c;
				maxR = i;
			}
		}
		System.out.println(maxR);
	}

 

你可能感兴趣的:(Project,Euler,Euler,算法)