Java: Program to start with an integer n, divide n by 2 if n is even or multiply by 3 and add 1 if n is odd, repeat the process until n = 1
Collatz Conjecture Simulation
Write a Java program starting with an integer n, divide it by 2 if it is even, or multiply it by 3 and add 1 if it is odd. Repeat the process until n = 1.
Sample Solution:
Java Code:
If input 5
Sample Output:
Input the value of n: 9 Value of n = 1
Flowchart:
For more Practice: Solve these Related Problems:
- Modify the program to count the number of steps to reach 1.
- Write a program to print the entire sequence instead of just the result.
- Modify the program to find the longest Collatz sequence under 1000.
- Write a program to visualize the Collatz sequence as a graph.
Go to:
PREV : String Starts with Word.
NEXT : Digit Sum in Words.
Java Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.