Reputation: 49
I tried implementing the Collatz Sequence using a while
loop, but I can't stop the sequence at 1. The code continues. I tried using all my possibilities, but I can't come up with a solution.
import java.util.Scanner;
public class cs{
public static void main(String[] args)throws Exception{
System.out.println("Starting number: ");
Scanner s = new Scanner(System.in);
int a = s.nextInt();
System.out.print(" " + a);
while(a>1)
{
if(a == 1) break; // this is not working though
if((a % 2 ) == 0) {
a = a / 2;
System.out.print(" " + a);
}
Thread.sleep(1000);
if((a % 2) != 0){
a = (a * 3) + 1;
System.out.print(" " + a);
}
Thread.sleep(1000);
}
}
}
Upvotes: 1
Views: 869
Reputation: 311853
Your loop is performing two steps in the Collatz sequence, instead of just one. Even if a
is 1
, it will then continue into the second if
, and turn it to 4
, so the loop will never terminate. Instead, you should use an else
clause, just just perform one step per iteration of the loop:
while (a > 1) {
if ((a%2) == 0) {
a = a / 2;
} else {
a = (a * 3) + 1;
}
Thread.sleep(1000);
System.out.print(" " + a);
}
Upvotes: 0
Reputation: 19
while (a > 1 && (a % 2) != 0){
a /= 2;
System.out.print(" " + a);
}
because if you have a look at your while condition, you will see that a
is bigger than 1 ==> can't be 1 at all, so, there is no need for the first if
statement.
import java.util.Scanner;
public class cs{
public static void main(String[] args)throws Exception{
System.out.println("Starting number: ");
Scanner s = new Scanner(System.in);
int a = s.nextInt();
System.out.print(" " + a);
while (a > 1 && (a % 2) != 0){
a /= 2;
System.out.print(" " + a);
}
}
Upvotes: 0
Reputation: 124704
The second if
condition here should be an else
of the first one:
if((a%2)==0){ // ... } // ... if((a%2)!=0){
Like this:
while (a > 1) {
if ((a % 2) == 0) {
a /= 2;
System.out.print(" " + a);
} else {
a = (a * 3) + 1;
System.out.print(" " + a);
}
}
I also removed the if (a == 1)
line which was pointless,
as due to the while (a > 1)
condition,
that if
would never be true
.
Lastly, I recommend to pay more attention to indenting your code correctly, and to add spaces around operators like I did, otherwise the code is too difficult to read, understand and debug.
Upvotes: 2
Reputation: 2103
The problem must be that a
never equals 1. Try printing the value of a
in each loop and see what it actually equals:
while(a > 1)
{
// This line is not required because if a == 1 then the while loop would terminate anyway:
// if(a==1) break; //this is not working though
if((a%2)==0){
a = a/2;
System.out.print(" "+a);
}
Thread.sleep(1000);
if((a%2)!=0){
a = (a*3)+1;;
System.out.print(" "+a);
}
Thread.sleep(1000);
System.out.println("a = " + a); // This checks what the value of a actually is
}
Upvotes: 1