Longest Collatz sequence

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

n n / 2 n → {n}/{2} \quad \quad (n is even)

n 3 n + 1 n → 3{n} + 1 \quad (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 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?

---- NOTE ----

  • Once the chain starts the terms are allowed to go above one million.

Try other problems Here


The answer is 837799.

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

1 solution

The last no in Java Solution is the answer with 525 no of terms.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import java.util.Arrays;

public class main {
    public static long collatz(long n){
        if(n%2==0){
            return (long)n/2;
        }else{
            return (long)(3*n+1);
        }
    }
    public static void main( String[] args) {
     long[] count= new long[1_000_000];
        Arrays.fill(count,1);
     long no,max=0;
     for(int i=1;i<1_000_000;i++) {
         no=i;
         while (no > 1) {
             count[i]++;
             no = collatz(no);
             }
             if(max<count[i]) {
                 System.out.println(i);
                 max = count[i];
             }
     }
        System.out.println("No of outputs are :"+max);
    }
}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import time
start = time.time()
def collatz(n, count=1):
    while n > 1:
        count += 1
        if n % 2 == 0:
            n = n/2
        else:
            n = 3*n + 1
    return count

max = [0,0]
for i in range(1000000):
    c = collatz(i)
    if c > max[0]:
        max[0] = c
        max[1] = i

elapsed = (time.time() - start)
print "found %s at length %s in %s seconds" % (max[1],max[0],elapsed)

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...