#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
typedef std::vector<int> int_vec;
typedef std::pair<int,int> int_pair;
typedef std::vector<int_pair> pair_vec;
int cycle_length(int number) {
int n = number, length = 1;
while (n != 1) {
if (n % 2 == 0) {
n /= 2;
}
else {
n *= 3;
++n;
}
++length;
}
return length;
}
int max_cycle_length(int_pair val) {
int_vec tmp;
for (int i = val.first; i <= val.second; ++i) {
tmp.push_back(cycle_length(i));
}
return *std::max_element(tmp.begin(), tmp.end());
}
int main () {
int a, b;
pair_vec numbers;
while (std::cin >> a >> b) {
numbers.push_back(std::make_pair(a, b));
}
for (pair_vec::iterator it = numbers.begin(); it != numbers.end(); ++it) {
std::cout << it->first << ' ' << it->second << ' ' << max_cycle_length(*it) << '\n';
}
return 0;
}
Refactorings
No refactoring yet !
Ants
February 16, 2011, February 16, 2011 00:03, permalink
What are the vectors used for other than temporary storage?
Here is a refactoring that removes their use. This also handles the case when the number passed to cycle_length() is zero or negative.
#include <iostream>
int cycle_length(int n)
{
int length = (n > 0) ? 1 : 0;
while (n > 1) {
n = (n % 2) ? (3 * n + 1) : (n / 2);
++length;
}
return length;
}
int max_cycle_length(int a, int b)
{
int max = 0;
for (int i = a; i <= b; ++i) {
int length = cycle_length(i);
if (length > max)
max = length;
}
return max;
}
int main ()
{
int a, b;
while (std::cin >> a >> b)
std::cout << a << ' ' << b << ' ' << max_cycle_length(a, b) << '\n';
return 0;
}
oussama
May 3, 2011, May 03, 2011 12:50, permalink
what is the worng here plz help
//3n+1 Problem
#include<iostream>
using namespace std;
int main()
{
int a;
int b;
while( cin >> a >> b )
{
int cycle = 0;
for(int i = b; i > a; i ++ )
{
if( b != a)
{
if( b % 2 == 0 )
{
b = b / 2;
cycle ++;
}
else
{
b = ( 3 * b ) + 1;
cycle ++;
}
}
else
;
}
cout<<cycle<<endl;
}
}
oussama
May 3, 2011, May 03, 2011 12:51, permalink
what is the worng here plz help
//3n+1 Problem
#include<iostream>
using namespace std;
int main()
{
int a;
int b;
while( cin >> a >> b )
{
int cycle = 0;
for(int i = b; i > a; i ++ )
{
if( b != a)
{
if( b % 2 == 0 )
{
b = b / 2;
cycle ++;
}
else
{
b = ( 3 * b ) + 1;
cycle ++;
}
}
else
;
}
cout<<cycle<<endl;
}
}
oussama
May 3, 2011, May 03, 2011 12:52, permalink
what is the worng here plz help
//3n+1 Problem
#include<iostream>
using namespace std;
int main()
{
int a;
int b;
while( cin >> a >> b )
{
int cycle = 0;
for(int i = b; i > a; i ++ )
{
if( b != a)
{
if( b % 2 == 0 )
{
b = b / 2;
cycle ++;
}
else
{
b = ( 3 * b ) + 1;
cycle ++;
}
}
else
;
}
cout<<cycle<<endl;
}
}
What improvements can be made to this solution?