PC110101(3n+1问题)(3n+1 Problem)

来源:互联网 发布:apache服务器源码下载 编辑:程序博客网 时间:2024/06/15 04:05

这里写图片描述
单纯模拟,用一个数组记录下“沿途”的值,避免重复运算。
注意:
1. 中间计算过程会超过int或long型数据所能表示的范围,故需要选择long long型整数.
2. 输入时可能较大的数在前面,需要调整顺序。
在中间计算过程中会超过 32 位整数表示范围的整数(括号内为循环节长度):
159487(184) 270271(407) 318975(185) 376831(330) 419839(162)
420351(242) 459759(214) 626331(509) 655359(292) 656415(292)
665215(442) 687871(380) 704511(243) 704623(504) 717695(181)
730559(380) 736447(194) 747291(248) 753663(331) 763675(318)
780391(331) 807407(176) 822139(344) 829087(194) 833775(357)
839679(163) 840703(243) 847871(326) 859135(313) 901119(251)
906175(445) 917161(383) 920559(308) 937599(339) 944639(158)
945791(238) 974079(383) 975015(321) 983039(290) 984623(290)
997823(440)

#include<cstdio>#include<iostream>using namespace std;long long f[1000000]={0};long long ss(long long x){    if (x<1000000)     if (f[x]!=0) return f[x];    else    {        if (!(x&1))             if ((x>>1)<1000000)                if (f[x>>1]!=0) return f[x]=f[x>>1]+1;                else return f[x]=ss(x>>1)+1;            else return ss(x>>1)+1;        else             if ((3*x+1)<1000000)                if (f[3*x+1]!=0) return f[x]=f[3*x+1]+1;                else return f[x]=ss(3*x+1)+1;            else return ss(3*x+1)+1;    }    else     {        if (!(x&1))             if ((x>>1)<1000000)                if (f[x>>1]!=0) return f[x>>1]+1;                else return ss(x>>1)+1;            else return ss(x>>1)+1;        else             if ((3*x+1)<1000000)                if (f[3*x+1]!=0) return f[3*x+1]+1;                else return ss(3*x+1)+1;            else return ss(3*x+1)+1;    }}int main(){    int m,n;    f[1]=1; f[2]=2;    while (cin>>m>>n)    {        long long max=-1; bool t=0;        if (m>n) {t=true; m=m+n; n=m-n; m=m-n;}        for (int i=m;i<=n;++i)        {            long long a=ss((long long)i);            if (a>max) max=a;        }        if (!t) printf("%d %d %d\n",m,n,max);        else printf("%d %d %d\n",n,m,max);    }    return 0;}
0 0
原创粉丝点击