Take any whole number greater than one.
1. If the number is odd, multiply it by three and add one.
2. If it is even divide it by two.
2a. If the result is still even, continue to divide by two until the result is odd.
3. Continue steps 1 and 2 until you get the same number twice.
[For example starting with 9 -> 28 -> 14 -> 7 which is considered one iteration. The next iteration brings this to 11.]
What number(s) does this process terminate at?
What starting value less than 200 takes the most iterations to terminate?
The source to the program I used is found below. However, it takes several hours to run up to and beyond 520,000,000. If you would like to modify it, post your version here, so I can maybe learn a bit more. I've only taken a Beginner's Programming Class in highschool, so I'm not very efficient yet. But here you go:
#include <iostream.h>
#include <stdlib.h>
#include <math.h>
using namespace std;
double loop(double);
int main()
{
int max = 0;
int minits = 0;
double number = 1;
double limit = 0;
int iterations = 0;
double counter = 1;
float step = 0.0;
int logs = 0;
cout << \"Enter the starting value: \";
cin >> counter;
cout << \"Enter the ending value: \";
cin >> limit;
cout << \"Enter the step: \";
cin >> step;
cout << \"Enter the minimum number of iterations: \";
cin >> minits;
while (counter <= limit)
{
number = counter;
iterations = 0;
while (int(number)!=1)
{
number = loop(number);
iterations+=1;
}
if (iterations>=minits)
{
if (fmod(counter,10000000.0)<1)
{
logs=log10(counter);
while (logs>=0)
{
cout << int(fmod(counter,pow(10,logs+1))/pow(10,logs));
logs--;
}
cout << endl;
}
else if (iterations>max)
{
cout << \"The number \";
logs=log10(counter);
while (logs>=0)
{
cout << int(fmod(counter,pow(10,logs+1))/pow(10,logs));
logs--;
}
cout << " took " << iterations << " iterations" << endl;
max=iterations;
}
}
counter+=step;
}
system("PAUSE");
return 0;
}
double loop(double number)
{
if (fmod(number,2.0)==1.0)
{
number*=3.0;
number=number+1.0;
}
while (fmod(number,2.0)<1)
number/=2.0;
return number;
}
|
Posted by Justin
on 2006-01-20 23:45:57 |