In: Computer Science
Java Collatz Conjecture (Timelimit: 3 seconds)
Problem Description
Write a Java program to solve the following problem.
The Collatz conjecture is about a sequence: start with any positive integer n. Then each term is obtained from the previous term as follows: if the previous term is even, the next term is one half the previous term. If the previous term is odd, the next term is 3 times the previous term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
| 1,if n = 1
f(n) = | f(3n + 1),if n is odd
| f(n/2),otherwise
Input:
The input is in ‘sequence.txt’. The first line of the input contains the line count m (1 ≤ m ≤ 1,000), which is the number of lines that follows the first line. Each of the following lines contains an integer n (1 ≤ n ≤ 10,000).
Sample input: (with periods at the end)
2.
12.
27.
Output:
The output consists of m lines. Each line prints the number of terms in the sequence of f(n) to a file 'output.txt'.
Sample output:
10.
112.
Information:
1. The expected complexity is unknown.
2. Write a code ‘A.java’ that reads ‘sequence.txt’ and writes the output in a file called ‘output.txt’.
3. The score will be 0 if your program does not terminate within 3 seconds.
Below is the JAVA code I hope that i have provided sufficient comments for your better understanding Note that I have done proper indentation but this code is automatically left alligned on this interface
import java.io.File;
import java.io.*;
import java.util.*;
public class A
{
static int collatzConjecture(int n)
{
//To keep track of how many elements have been traversed
int count = 1;
//loop till number do not becomes 1
while (n != 1)
{
//Check if n is odd
if (n%2==1)
n = 3 * n + 1;
//n is even
else
n = n / 2;
count++;
}
return count;
}
public static void main(String []args) throws IOException
{
Scanner scanner = new Scanner(new File("sequence.txt"));
//read number of lines in file
int n = scanner.nextInt();
//create an array of size n to hold numbers from text file
int[] input = new int[n];
int i = 0; //To store index
while(scanner.hasNextInt())
{
input[i++] = scanner.nextInt();
}
//create an array of size n to store number of terms in
sequence
int[] result = new int[n];
for(i=0;i<n;i++)
result[i] = collatzConjecture(input[i]);
//open output file
FileWriter writer = new FileWriter("output.txt");
//Traverse the result array and store it in output file
for(int element: result)
writer.write(element + System.lineSeparator());
writer.close();
}
}
Below is the screenshot of output
I have tried to explain it in very simple language and I hope that i have answered your question satisfactorily.Leave doubts in comment section if any