• 3n+1问题


    普通循环代码(c语言)

    size_t treeN (size_t i)
    {
        if (i < 1)
        {
            return 0;
        }
        size_t num = 1;
        size_t n = i;
        printf("%d
    ",n);
        while (n != 1)
        {
            if (n % 2 == 0)
            {
                n = n / 2 ;
            }else
            {
                n = 3 * n + 1;
            }
            num ++;
            printf("%d
    ",n);
        }
        return num;
    }

    数组递归调用

    size_t treeN2(int* p,int n)
    {
        int* position = p;
        size_t L = 1;
        int number = n;
    
        while (number >= n)
        {
            if (number % 2 == 0)
            {
                number = number / 2;
            }else
            {
                number = number * 3 + 1;
            }
            L++;
        }
    
        if (*(p+number) == 0)
        {
            if (number % 2 == 0)
            {
                *(p+number) = treeN2(p,number/2) + L;
            }else
            {
                *(p+number) = treeN2(p,number * 3 + 1) + L;
            }
            
        }
    
        return *(p+number);
    }

    主函数

    int main()
    {
        int res1  = treeN(100);
        int a[100] = {0}; //先创建一个所求数大小的数组
        a[1] = 1; // 将1位置初始化为1
        int res2 = treeN2(a,100) + 1; 
    
        return 0;
    }

  • 相关阅读:
    P1171 售货员的难题--搜索(剪枝)
    逆元-P3811 【模板】乘法逆元-洛谷luogu
    gcd和exgcd和lcm
    递推
    Docker hello workd
    Docker配置文件详解
    Centos7变动
    centos7安装docker
    nginx性能调优
    nginx相关
  • 原文地址:https://www.cnblogs.com/jackzone/p/8964965.html
Copyright © 2020-2023  润新知