Uva's 3n+1 problem

前端 未结 8 1993
滥情空心
滥情空心 2020-12-11 22:40

I\'m solving Uva\'s 3n+1 problem and I don\'t get why the judge is rejecting my answer. The time limit hasn\'t been exceeded and the all test cases I\'ve tried have run corr

8条回答
  •  南笙
    南笙 (楼主)
    2020-12-11 23:22

    If I understand correctly you are using a memoizing approach. You create a table where you store full results for all the elements you have already calculated so that you do not need to re-calculate results that you already know (calculated before).

    The approach itself is not wrong, but there are a couple of things you must take into account. First, the input consists of a list of pairs, you are only processing the first pair. Then, you must take care of your memoizing table limits. You are assuming that all numbers you will hit fall in the range [1...1000001), but that is not true. For the input number 999999 (first odd number below the upper limit) the first operation will turn it into 3*n+1, which is way beyond the upper limit of the memoization table.

    Some other things you may want to consider are halving the memoization table and only memorize odd numbers, since you can implement the divide by two operation almost free with bit operations (and checking for even-ness is also just one bit operation).

提交回复
热议问题