---
title: "Project Euler p14 - Longest Collatz sequence"
author: "mysh"
date: "2013-10-08T17:32:51Z"
tags: []
categories: ["编程语言"]
slug: "project-euler-p14-longest-collatz-sequence"
draft: false
lastmod: "2013-10-08T17:32:51Z"
id: 1953360
url: "https://mysh.iteye.com/blog/1953360"
---

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

[http://projecteuler.net/problem=14](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);
	}
```