#include "stdafx.h"
#include <cstdlib>
#include <iostream.h>
#include <time.h>
#include <math.h>
void mathcode1(int n)
{
while(n>=1)
{
if(n==1)
{cout<<n<<endl;
break;}
else if((n>1)&&(n%2==0))
{cout<<n<<"-";n=n/2;}
else if((n>1)&&(n%2==1))
{cout<<n<<"-";n=n*3+1;}
}
}
int main()
{
int N,i;
long set;
cin>>N;
if(N==0){cout<<"0";return 0;}
for(i=N;i>1;i--)
{mathcode1(i);}
system("PAUSE");
return EXIT_SUCCESS;
}
执行效果
改进:对于10000测试的时候,半分钟才能搞定,这个算法的优化,思路已有,不过还得靠STL了。。。
#include "stdafx.h"
#include <cstdlib>
#include <iostream.h>
#include <time.h>
#include <math.h>
void mathcode1(int n)
{ int count1=1;
int t=n;
while(n>=1)
{
if(n==1)
{ cout<<t<<"the step is:"<<count1<<endl;
// cout<<n<<endl;
break;}
else if((n>1)&&(n%2==0))
{//cout<<n<<"-";
count1++;n=n/2;}
else if((n>1)&&(n%2==1))
{//cout<<n<<"-";
count1++;n=n*3+1;}}
}
int main()
{
int N,i;
long set;
cin>>N;
if(N==0){cout<<"0";return 0;}
for(i=N;i>1;i--)
{mathcode1(i);}
system("PAUSE");
return EXIT_SUCCESS;
}