I´ve made a program that does the (usually called) hailstone sequence, The program basically does this:
creates an int (value) and assign it a value.
If the int is even, divide it by two.
If the int is odd, multiply it by three and add one. Continue this process until n is equal to one.
it seems to be working fine with most numbers, but this number 99888769, the app hangs on a negative integer. Why is this?, they say that no-one has yet been able to proove that it stops, I´m not expecting I have solved that. But would be interesting to know why my app stops. -
private void hailStoneSequence(){
int value = 99888769;
int i = 0;
boolean trueOrFalse = isOddOrEven (value);
while (value != 1){
while (trueOrFalse == true && value != 1){
i++;
int previousValue = value;
value = value / 2;
println( previousValue +" is even, so I take half: "+value);
trueOrFalse = isOddOrEven (value); // returning true or false, and inserting the newly divided number. So that it breaks loop when nescesary.
}
while (trueOrFalse == false && value != 1){
i++;
int previousValue = value;
value = (value * 3) + 1;
println (previousValue +" is odd, so I make 3n+1: "+value);
trueOrFalse = isOddOrEven (value);
}
}
println ("\n\nThe process took "+i+" to reach "+value);
}
private boolean isOddOrEven(int value){
/*
* Takes an value and returns true, if that number is even.
* Else it returns false.
*/
if (value % 2 != 0){
return false;
}else{
return true;
}
}
}
解决方案
As you keep increasing ints, they will eventually (in what might seem like a startling behavior) become negative because you are surpassing the maximum value of the int type (2^31-1), i.e. you end up changing the bit (of the int's binary representation) that is used to store the sign of the number. Use long instead.