-6

I cannot find the bug in this code. If it were not for Project Euler ruling my answer as incorrect, I would swear to the heavens that my code is right.

I could use another approach, but this problem is not all that complex, and yet I have been utterly defeated trying to find the bug.

The question is :

The following iterative sequence is defined for the set of positive integers:

n → n/2 (n is even) n → 3n + 1 (n is odd)

Using the rule above and starting with 13, we generate the following sequence:

13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.

Which starting number, under one million, produces the longest chain?

My code is :

public class CollatzSequence014 {

public static void main(String [] args){
    long start = System.currentTimeMillis();
    long maxTotal = 0;
    long inputNum = 0;

        for (long i = 3; i < 1000000 ; i++){
            long total = generateSequence(i);
            if (total > maxTotal){
                inputNum = i;
                maxTotal = total;
            }
        }
    long end = System.currentTimeMillis();

    System.out.println("The input number was : " + inputNum + " and the total was " + maxTotal);
    System.out.println("Time taken : " + (end - start) + "ms");
}



public static long generateSequence(long n){
    long counter = 0;
    long currentDigit = n;

    while (currentDigit > 1){
        counter++;
        if (n % 2 == 0){
             currentDigit = currentDigit / 2;
        }
        else {
            currentDigit = (3 * currentDigit) + 1;
        }
    }
    return counter;
}

}

Huntro
  • 322
  • 1
  • 3
  • 16
BenParker93
  • 51
  • 1
  • 1
  • 3
  • What error/output are you getting? Is there actually an error, or does this just time out? – Mureinik Sep 19 '16 at 08:28
  • 2
    Possible duplicate of [What is a debugger and how can it help me diagnose problems?](http://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Raedwald Sep 19 '16 at 08:38

3 Answers3

3

You have to check if the currentDigit is even, not n.

if(currentDigit % 2 == 0)
Huntro
  • 322
  • 1
  • 3
  • 16
0

First, how you should look for the bug: try outputting the sequence (not just the length) for small n (e.g. 13, since the problem already gives you the correct sequence there). You'll see that you get 13, 40, 121... and that should already tell you where the bug is.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
0

error is here :

if (n % 2 == 0){

should be :

if (currentDigit % 2 == 0){
Ji aSH
  • 3,206
  • 1
  • 10
  • 18