小编nob*_*ody的帖子

项目Euler#14:为什么我的TreeMap算法比蛮力慢?

背景:几年前我在学校里第一次学习C++和Java,但是在过去9年左右的时间里我没有做太多编程,因为我以前的职业生涯并不需要它.

我决定调查项目Euler以完善我的编程并解决问题14,该问题要求找到具有最长Collat​​z序列的1到100万之间的整数.(Collat​​z序列继续进行,给定起始编号,将数字乘以3,如果奇数则加1,或者如果数字为偶数则将数字减半.过程继续,直到数字达到1.)

我首先使用蛮力解决了这个问题,如下面的代码所示.

int n;
long temp; // long is necessary since some Collatz sequences go outside scope of int
int[] n_length = new int[1000000];
    for(n = 0; n < 1000000; n++){
        temp = n + 1;
        n_length[n] = 1;
        while (temp > 1){
            n_length[n]++;
            if (temp % 2 == 0) temp = temp/2;
            else temp = 3*temp + 1;

        }
    }
int max = 0;
    int max_index = 0;
    for (int i = 0; i < 1000000; i++){
        if …
Run Code Online (Sandbox Code Playgroud)

java algorithm performance

12
推荐指数
1
解决办法
508
查看次数

标签 统计

algorithm ×1

java ×1

performance ×1