Project Euler 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.
正の整数に以下の式で繰り返し生成する数列を定義する。

n → n/2 (n が偶数)

n → 3n + 1 (n が奇数)

13からはじめるとこの数列は以下のようになる。

13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
13から1まで10個の項になる。 この数列はどのような数字からはじめても最終的には 1 になると考えられているが、まだそのことは証明されていない(コラッツ問題)

さて、100万未満の数字の中でどの数字からはじめれば一番長い数列を生成するか。

注意: 数列の途中で100万以上になってもよい

Mathematica

Ans = {};
Ans = Table[
   A = i;
   L = {};
   While[A != 1,
     L = Append[L, A];
     If[EvenQ[A] == True,
      A = A/2,
      A = 3 A + 1
      ]
     ]
    L = Append[L, A];
   Length[L],
   {i, 1000000}
   ];
Position[Ans, Max[Ans]]

Ans には1から1000000までの、数列の長さをいれることになります。

A が問題で言う n にあたる変数で、L には A の値がどんどん付け加えられていきます。

最後に

Position[Ans,Max[Ans]]

で、Ansの中で最も数が大きいものの位置を返します。

C/C++

#include <iostream>
using namespace std;

int main(){
	const int SIZE = 1000000;
	int count, max = 0, maxnum;
	__int64 n;
	for(int i=2 ; i<SIZE ; i++){
		count = 0;
		n = i;

		while(n!=1){
			if(n%2==0) n /=2;
			else n= 3*n + 1;
			count++;
		}
		if(max < count){
			max = count;
			maxnum = i;
		}
	}

	cout << maxnum << endl;
}

最初は配列を宣言して、計算を再利用していたのですが、int型の100万個の配列は宣言できなかったので、やむなくこのような形に。
計算途中で n が intの範囲を飛び出すことがあるので、 __int64型にしてあります。

追記
#include <iostream>
#include <deque>
using namespace std;

int main(){
	const int SIZE = 1000000;

	int count;
	__int64 n;
	deque<int> arr(SIZE, 0);

	// コラッツ
	for(int i=2 ; i<SIZE ; i++){
		count = 0;
		n = i;

		while(1){
			if(n%2==0) n /= 2;
			else n = 3*n + 1;
			
			count++;

			if(n<SIZE && arr[(unsigned int)n]!=0){
				count += arr[(unsigned int)n];
				break;
			}
			else if(n==1) break;
		}
		arr[i] = count;
	}


	int max=0, maxnum;
	for(int i=0; i<SIZE ; i++){
		if(max < arr[i]){
			max = arr[i];
			maxnum = i;
		}
	}
	
	cout << maxnum << endl;

	return 0;
}

配列は無理だけどdequeだったら100万個程度余裕だぜ!ということらしい。
100万個だと、dequeへのアクセス速度の問題か、ただ単に毎回計算している方が速いようです。