The 3n+1 problem
思想,先將範圍之內數的週期計算並將其放在數組中存儲下來,比較的時候直接調用,且已知0和1根據此算法的週期都爲0,所以,取定一個範圍,定義數組的下標從2開始,即a[n]對應n 的週期,利用下標,可以方便的調用該數的週期,方便接下來的調用比較。
數組的提前定義存儲,並在之後的計算中調用,可以避免重複計算,節省運算時間。
#include<stdio.h>
#define N 100001int main()
{
long long int i,j,max,n,m,k,high,low,count;
long long int a[N]={0};
//a[0]=0;
//a[1]=0;
for(i=2;i<=N;i++)
{
k=i;
count=1;
while(k!=1)
{
if(k%2==1)
k=3*k+1;
else
k/=2;
count++;
}
a[i]=count;
}
while(scanf("%lld %lld",&n,&m)!=EOF)
{
max=0;
low =m<n?m:n;
high=m>n?m:n;
for(j=low;j<=high;j++)
{
if(a[j]>max)
max=a[j];
}
printf("%lld %lld %lld\n",low,high,max);
}
}