0
collatz conjecture
ques: 1: Take any natural number 2: If it's even, half it, otherwise triple it and add one 3: Repeat step 2, until you reach 4, 2, 1 sequence 4: You will always reach 1, eventually code in java>> package hello; import java.util.*; public class cha { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scanner = new Scanner(System.in); System.out.println("Enter any number: "); int x = scanner.nextInt(); while (x != 0) { System.out.println(x); if(x % 2 == 0) { x = x/2; }else { x = 3 * x + 1; System.out.println(x); } } } } How can I break the loop? Any help
5 Réponses
+ 1
so 1 should be the last digit right ?
then break the loop when x reach 1
+ 1
Input = 1 --> print 1 4 2 1
Change your while loop --> while(x != 1)
+ 1
i got it thanks
0
Can you give me the code?
0
package hello;
import java.util.*;
public class cha {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
System.out.println("Enter any number: ");
int x = scanner.nextInt();
while (x != 0) {
System.out.println(x);
//added
if(x==1){
break;
}
if(x % 2 == 0) {
x = x/2;
}else {
x = 3 * x + 1;
System.out.println(x);
}
}
}
}