Help Me Please!!

I have to write a program to find the longest "number chain" for any given max number
"number chain" is computed in this way: if the number is even, the next number is that number divided by 2, if the number is odd, the next number is that number times 3 then add 1, the chain ends when "4" is reached
for example: 16-8-4, 7-22-11-34-17-52-26-13-40-20-10-5-16-8-4
your program will count the length of the chain
your program will take in one number from the end user, use that number as the max number for the search
your program will output number chains along its search and end with this kind of output: "7 gives the longest number chain, the length is 15"

I have everything except for the part about comparing them to find the largest number chain. I can't seem to figure it out.

This is what i have for the code so far.
<#include <iostream>
using namespace std;

int main() {
int maxnumber;
float r;
int a = 0;
int num = 0;
int numIteration=1;
int length;
cout << "Enter your max number.";
cin >> maxnumber;

while (numIteration <= maxnumber){
length = 0;
num = numIteration;
a=0;
cout << num;

while (a == 0){
r = num%2;
if (num == 4){
a=1;
cout << endl;

}
else if (r == 0){
num = num/2;
cout <<"-" << num;

}
else if (r == 1){
num = num*3 + 1;
cout << "-" << num;
}
length = length + 1;
}
numIteration=numIteration +1;
cout << "The length of this chain is: " << length << endl;
}
return 0;
}
>

Any help with this would be amazing!
Last edited on
closed account (48T7M4Gy)
Please use <> code tags around your code.

Declare two variables int max and int startNumber.

Each time you run a number compare the number of steps for that one against max and if it is greater then update the two variable. Since no number produces 0 steps intialize max = 0.
Topic archived. No new replies allowed.