Problem 14

算法描述
The following iterative sequence is defined for the set of positive integers:

n  n/2 (n is even)
n  3n + 1 (n is odd)

Using the rule above and starting with 13, we generate the following sequence:

13  40  20  10  5  16  8  4  2  1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.

Which starting number, under one million, produces the longest chain?

NOTE: Once the chain starts the terms are allowed to go above one million.



问题分析:
从1到1000000依次计算其长度,然后在查找的过程中比较,计算,这个最简单。
当然了~从小到大计算的过程中,肯定会有重复计算的。
例如:
13 ->40 ->20 ->10 ->5 ->16 ->8 ->4 ->2 ->1得到了长度10,
但是之前计算10 ->5 ->16 ->8 ->4 ->2 ->1得到了长度7
这样计算13便可以通过13 ->40 ->20的长度 + 10的长度 = 10

	public static Long count_chain(Long number) {
		Long result = 0L;
		Long init = number;
		while (number != 1) {
			if (!total.containsKey(number)) {
				if (number % 2 == 0) {
					number = number / 2;
					result++;
				} else {
					number = 3 * number + 1;
					result++;
				}
			}else{
				result += total.get(number);
				total.put(init, result);
				break;
			}
		}
		total.put(init, result);
		return result;
	}
	
	public static long find_max(){
		long maxLength = 0L;
		long maxNumber = 0L;
		Iterator<Long> iter = total.keySet().iterator();
		while(iter.hasNext()){
			long key = iter.next();
			long value = total.get(key);
			if(value>maxLength){
				maxLength = value;
				maxNumber = key;
			}
		}
		
		return maxNumber;
	}
	

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