moosemaster23
New Member
- Joined
- Feb 15, 2013
- Messages
- 10
ok so I've got this code which is aiming to work out the length of the first n collatz sequences. See: Collatz conjecture - Wikipedia, the free encyclopedia
Essentially for a given integer x, the sequence is as follows:
first term: x
second term: if x is even, x/2, if x is odd, 3x+1
continue until you get to 1
My code tries to do the following:
Going through the numbers 1 to n it checks whether I've already calculated the length of the sequence starting with n, if so it goes to the next number (n+1), if it has not calculated the length of the sequence starting with n then it runs through the sequence until hitting a number which we do have the length of. It then puts in all the values of these numbers into my array. It stops when the second column of the array is full (second column is either 0 or 1, 0 representing a number whose sequence length I haven't found and 1 representing a number whose sequence length I've found.
The bit that I'm having troubles with is in the middle (high lighted in bold). The code is not stopping when f(k,2)=1, instead (for 3 for example the code gives the following output:
3
10
5
16
8
4
2
1
4
2
1
4
2
1
4
2
1
...
Any ideas on how to fix?
Essentially for a given integer x, the sequence is as follows:
first term: x
second term: if x is even, x/2, if x is odd, 3x+1
continue until you get to 1
My code tries to do the following:
Going through the numbers 1 to n it checks whether I've already calculated the length of the sequence starting with n, if so it goes to the next number (n+1), if it has not calculated the length of the sequence starting with n then it runs through the sequence until hitting a number which we do have the length of. It then puts in all the values of these numbers into my array. It stops when the second column of the array is full (second column is either 0 or 1, 0 representing a number whose sequence length I haven't found and 1 representing a number whose sequence length I've found.
The bit that I'm having troubles with is in the middle (high lighted in bold). The code is not stopping when f(k,2)=1, instead (for 3 for example the code gives the following output:
3
10
5
16
8
4
2
1
4
2
1
4
2
1
4
2
1
...
Any ideas on how to fix?
Code:
Sub problem()
n = Cells(1, 2).Value
ReDim f(1 To n, 1 To 2)
ReDim g(1 To n)
f(1, 1) = 1
f(1, 2) = 1
l = n
m = 1
Do Until Application.WorksheetFunction.Sum(g) = n
If f(m, 2) = 0 Then
k = m
x = 1
[B] Do Until f(k, 2) = 1
Cells(x, 3) = k
Cells(x, 4) = x
If k Mod 2 = 0 Then
k = k / 2
Else
k = 3 * k + 1
End If
x = x + 1
If k > l Then
ReDim f(1 To k, 1 To 2)
End If
Loop[/B]
For r = 1 To x - 1
f(Cells(r, 3).Value, 1) = f(k, 1) + x - Cells(r, 4).Value
f(Cells(r, 3).Value, 2) = 1
Next
End If
For i = 1 To n
g(i) = f(i, 2)
Next
m = m + 1
Loop
End Sub