user2175076
user2175076

Reputation: 59

3n + 1 failed for unknown reason

I am doing the programming challenges of which I am doing the 3n + 1 challenge. I ahve completed code for it and it works fine for me completely BUT on the website it keeps saying that I have the wrong answer.I have no idea why if anyone can give me a reason for this it would be a great help. Code is below.

import java.util.*;
import java.io.*;

class Conjecture {

    public static void main(String[] args) throws IOException {

        int array[] = new int[8];
        int finalCounter = 0;
        int currentCounter = 0;

        Scanner scanner = null;

        try {
            scanner = new Scanner(
                    new BufferedReader(new FileReader("text.txt")));

            int counter = 0;
            while (scanner.hasNext()) {
                array[counter] = scanner.nextInt();
                counter++;
            }
        } finally {
            if (scanner != null) {
                scanner.close();
                System.out.println("done");
            }
        }

        for (int loop = 0; loop < array.length; loop += 2) {
            int i = array[loop];
            int j = array[loop + 1];
            finalCounter = 0;
            for (int k = i; k < j; k++) {
                int x = k;
                currentCounter = 0;
                while (x != 1) {

                    if (x % 2 == 0) {
                        x = x / 2;
                        currentCounter++;
                    } else if (x % 2 == 1) {

                        x = x * 3 + 1;
                        currentCounter++;
                    }

                    if (currentCounter > finalCounter) {
                        finalCounter = currentCounter;
                    }

                }

            }
            System.out.println(i + " " + j + " " + (finalCounter + 1));
        }

    }
}

Upvotes: 0

Views: 76

Answers (1)

vz0
vz0

Reputation: 32923

Instead of reading from file.txt, you should read the input from System.in. Since the problem statement does not says the number of test cases, you should process each case at the moment of reading the case. Your array is just 8 elements long, and I'm pretty sure there is going to be more test cases.

Upvotes: 1

Related Questions