D28. 題目練習
這次一樣是練3n+1的題目,之前是用C語言,這次用C++來寫
#include<iostream>
using namespace std;
int main()
{
int n;
cin>>n;
while(n!=1){
if(n%2==0){
n=n/2;
}
else{
n=n*3+1;
}
cout << n <<" ";
}
cout << endl;
return 0;
}
進階(uva100)
#include<iostream>
using namespace std;
int main()
{
int a,x,y,n,i,j,count=1,max=1;
while(cin>>i)
{ cin>>j;
count=1;max=1;
if(i>j)
{
cout<<i<<" "<<j<<" ";
x=i;
i=j;
j=x;
}
else
cout<<i<<" "<<j<<" ";
for(a=i;a<=j;a=a+1)
{
n=a;count=1;
while(n!=1){
if(n%2==1)
{
n=n*3+1;
count=count+1; }
else
{
n=n/2;
count=count+1; }}
if(count>max) {max=count;}
}
cout<< max<<endl;
}
return 0;
}
跟C語言的差別其實只在輸入輸出的地方而已,所以在語言轉換過程並不難