Note that there are some explanatory texts on larger screens.

plurals
  1. PO3n+1 challenge at UVa
    primarykey
    data
    text
    <p>I'm having trouble running the "3n+1 Problem" from the "Programming Challenges" <a href="http://programming-challenges.com/pg.php?page=downloadproblem&amp;probid=110101&amp;format=html" rel="nofollow">book</a>.</p> <p>I've tried every solution in Java I could find on google (even the ones on Stack Overflow), and not a single one works, they all report a "Wrong answer". I also found a working C++ solution, translated it to Java, and same thing: "Wrong answer".</p> <p>I'm using the template from Programming Challenges for Java <a href="http://programming-challenges.com/pg.php?page=javainfo" rel="nofollow">submissions</a>, and I could swear my algorithm is right, the only possible problem I can think of is in the code for reading the input or writing the output, but I can't figure it out. Here's my code, any help would be greatly appreciated:</p> <pre><code>class myStuff implements Runnable { @Override public void run() { String line = Main.ReadLn(128); while (line != null) { process(line); line = Main.ReadLn(128); } } private void process(String line) { String[] data = line.split("\\s+"); if (data.length == 2) { int low = Integer.parseInt(data[0]); int high = Integer.parseInt(data[1]); int max = low &lt; high ? findMax(low, high) : findMax(high, low); System.out.println(low + " " + high + " " + max); } } private int findMax(int low, int high) { int max = Integer.MIN_VALUE; for (int i = low; i &lt;= high; i++) { int length = cycleLength(i); if (length &gt; max) max = length; } return max; } private int cycleLength(int i) { long n = i; int length = 1; while (n &gt; 1) { n = ((n &amp; 1) == 0) ? n &gt;&gt; 1 : 3*n + 1; length++; } return length; } } // java program model from www.programming-challenges.com class Main implements Runnable { static String ReadLn(int maxLength) { // utility function to read from // stdin, Provided by Programming-challenges, edit for style only byte line[] = new byte[maxLength]; int length = 0; int input = -1; try { while (length &lt; maxLength) { // Read untill maxlength input = System.in.read(); if ((input &lt; 0) || (input == '\n')) break; // or untill end of line ninput line[length++] += input; } if ((input &lt; 0) &amp;&amp; (length == 0)) return null; // eof return new String(line, 0, length); } catch (java.io.IOException e) { return null; } } public static void main(String args[]) { // entry point from OS Main myWork = new Main(); // Construct the bootloader myWork.run(); // execute } @Override public void run() { new myStuff().run(); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload