Algorithm, Data structure/Solved Algorithmic Problem

Project Euler #14 - Longest Collatz sequence

JaykayChoi 2016. 6. 16. 00:30

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.



출처: https://projecteuler.net/



양의 정수가 주어졌을 때 위와 같은 규칙을 통하면 몇 번의 과정을 통해 숫자 1이 된다고 합니다. 1,000,000 이하의 수로 시작했을 때 1까지 도달하는데 가장 긴 과정을 거치는 숫자를 구하는 문제입니다.

memoization 을 사용해 시간 복잡도를 줄이는 방법을 사용했습니다.



my solving

c++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
using namespace std;
typedef long long ll;
 
const int MAX_INT = 1000000;
int cache[MAX_INT + 1];
 
int memoization(int number)
{
    int ret = 0;
    ll num = number;
    
    while (true)
    {
        if (num < MAX_INT && cache[num] != -1)
        {
            ret += cache[num];
            break;
        }
 
        if (num % == 0)
            num = num / 2;
        else
            num = * num + 1;
        ret++;
    }
 
    cache[number] = ret;
 
    return ret;
}
 
int main() 
{
    int maxCount = 0;
    int ret = 1;
 
    memset(cache, -1sizeof(cache));
    cache[1= 1;
 
    for (int i = 2; i <= MAX_INT; i++)
    {
        int count = memoization(i);
        if (count > maxCount)
        {
            maxCount = count;
            ret = i;
        }
    }
 
    cout << ret << endl;
 
    system("pause");
    return 0;
}
cs