考拉兹猜想,100万以内的数

时间:2021-06-25 17:25:25   收藏:0   阅读:0
import java.util.ArrayList;
import java.util.Arrays;

import java.util.List;

/**
 * @author: small-sunshine
 * @Description:考拉兹猜想,100万以内的数 考拉兹猜想是1927年提出的猜想:
 * 一个正整数,如果是奇数就乘以3再加1,如果是偶数就除以2,这样经过若干个次数,最终回到1。
 * @date: 2021/6/25 1:00 下午
 */
public class CollatzConjecture {

    public static int num = 1000 * 1000;
    
    public static List<Integer> count = new ArrayList();
    
    public static int[] array = new int[num];

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        for (int i = 1; i < num; i++) {
            array[i] = kill(i, 1);
        }
        int[] arrayCopy = Arrays.copyOf(array, num);
        Arrays.sort(array);
        for (int i = 1; i < num; i++) {
            if (arrayCopy[i] == array[num - 1]) {
                count.add(i);
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("用时:" + (end - start) + "ms");
        System.out.println(String.format("这些数:%s 的序列最多是:%d", count.toString(), array[num - 1]));
    }
    
    /**
     * 考拉兹猜想-递归处理三个条件
     * 1、一个问题的解可以分解为几个子问题的解
     * 2、这个问题与分解之后的子问题,除了数据规模不同,求解思路完全一样
     * 3、存在递归终止条件
     *
     * @param i
     * @return int
     */
    public static int kill(int i, int count) {
        if (i <= 0) {
            return 0;
        }
        if (i == 1) {
            return count;
        }
        int j = i % 2 == 0 ? i / 2 : 3 * i + 1;
        count++;
        return kill(j, count);
    }
}

运行结果:

用时:437ms
这些数:[910107] 的序列最多是:476

 

评论(0)
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!