Hi, I am suppose to create a code that takes the values between 1-1000 and produces the hailstone sequence for them, then it prints out the initial value that produced the longest sequence along with the sequence's length. I have tried to use an array but it didn't seem to work, so I tried a simpler approach but it's not working either:

``````public class one {
public static void main(String[]args){
int first=1;
int last=1000;
int max=0;
int length=0;

while (first<=last){

while (first!=1)
{
if (first%2== 0)
{
first= first / 2;
length++;
}
if (first % 2 != 0)
{
first = (3 * first) + 1;
length++;
}
}
first++;
break;
}

if (max < length)
{
max = length;
}

System.out.println(max+first);

}

}``````

Thank you for any help!

Are you sure that you need to find for each number from 1 to 1000??? I know that any starting number will eventually reach "1" at the end of computation.

Anyway, line 17 should be "else" instead of "if" alone.

Are you sure that you need to find for each number from 1 to 1000??? I know that any starting number will eventually reach "1" at the end of computation.

Anyway, line 17 should be "else" instead of "if" alone.

Yes, I am sure. It says a program that finds the starting value in the range 1 to 1000 to produce the longest sequence.
I already changed the 'if' to 'if else'. I am trying to play around with it but I can't seem to get it to work.

OK, I'm done with the code. The answer for the number is 871 with 178 length.

Your "first" variable is tampered and cause the loop to go infinitely. To be sure that your loop counter wouldn't be tampered, you should use a "for" loop, so it is clearer.

``````for (int i=2; i<last; i++) {  // the "i" is the starting number of each Hailstone
first = i;
length = 0;
while (first>1) {
...
}
// after the loop, check whether or not the new length is greater than the
// current max you have. If so, replace it, and also keep the number "i"
// as the biggest number as well
}``````

OK, I'm done with the code. The answer for the number is 871 with 178 length.

Your "first" variable is tampered and cause the loop to go infinitely. To be sure that your loop counter wouldn't be tampered, you should use a "for" loop, so it is clearer.

``````for (int i=2; i<last; i++) {  // the "i" is the starting number of each Hailstone
first = i;
length = 0;
while (first>1) {
...
}
// after the loop, check whether or not the new length is greater than the
// current max you have. If so, replace it, and also keep the number "i"
// as the biggest number as well
}``````

Fantastic! Thanks a lot, you've made me understand loops much better than the teacher. It's so simple though, I feel like an idiot, but thanks a bunch. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.