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

21st Apr 2019, 10:52 AM
Deepesh Subba
Deepesh Subba - avatar
5 ответов
+ 1
so 1 should be the last digit right ? then break the loop when x reach 1
21st Apr 2019, 11:17 AM
Taste
Taste - avatar
+ 1
Input = 1 --> print 1 4 2 1 Change your while loop --> while(x != 1)
21st Apr 2019, 11:24 AM
Denise Roßberg
Denise Roßberg - avatar
+ 1
i got it thanks
21st Apr 2019, 11:25 AM
Deepesh Subba
Deepesh Subba - avatar
0
Can you give me the code?
21st Apr 2019, 11:24 AM
Deepesh Subba
Deepesh Subba - avatar
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); } } } }
21st Apr 2019, 11:28 AM
Deepesh Subba
Deepesh Subba - avatar