Thursday, January 13, 2011

100 - The 3n + 1 problem

pseudocode and algorithm is not the code to submit your solution.

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=121&page=show_problem&problem=36

Pseudocode for 3n+1(brute force)
input first integer, second integer
if first > second, then:
start = second
end = first
else:
start = first
end = second

max = 0

for i=start to i=end:
n=i
counter=1
while n not equal to 1:
if n is odd number,then :
n = (3*n)+1
counter + 1
else:
n = n/2
counter + 1
if counter > max,then:
max=counter

output answer


precaution part :
1) use unsigned int
2) input until eof, while(cin>>x>>y)
3) brute force able to solve the question :-)

faster algorithm
pre-generate the list of cycle length from 1 to 1,000,000.
find the max of the cycle length within the pairs of integers given.

even faster algorithm(DP approach)
pre-generate the list from 1 to 1,000,000.
during pre-generating list, save the number during the operation for odd/even and fill in the cycle length after getting the 1
1 = 1
2 1 = 2

3 10 5 16 8 4 2 1 = 8 << from here , we can actually know that the cycle length of

2 = 2
4 = 3
8 = 4
16 = 5
5 = 6
10 = 7
save it into the list and we don't have to generate the same thing again.
If during the pre-generating list, the numbers which is generated can be reuse where add in the sum into the cycle length.

1 = 1
2 1 = 2
3 10 5 16 8 4 2 1 = 8
4 = 3
5 = 6
6 3 = 9 << at this stage, number 3 is generated before, we can add in the cycle length of 3 which is 8 with the current cycle length of 1, 1+8=9

P/S : Correct me if im wrong. :-)

No comments:

Post a Comment