297 Collatz in the Range

Back to General discussions forum

sam_bandara     2022-09-28 06:26:07

Hi Experts,

I used the following methods to optimize the timing.

1. Removed all even numbers
2. Filtered some modulos 
value % 2 == 0 or (value - 2) % 3 == 0 or (value - 4) % 9 == 0 or (value - 5) % 9 == 0 or (
            value - 8) % 9 == 0
3.Sieve table of 2^23

but still, my program takes ~90S to process (far away from the allowed time of 60S). Appreciate it if you suggest any optimization tricks.

Cheers, Sam

gardengnome     2022-09-28 07:58:46
User avatar

No optimisation on my part. My code contains the follwoing comment: "run with pypy for acceptable speed". See pypy.

gardengnome     2022-09-28 17:54:41
User avatar

To quantify this a bit, here is an example run: 265 seconds with standard Python, 9 seconds with pypy (30 times faster!), and 4 seconds with java open jdk. There is room for improvement (e.g. caching), but brute force works in this case.

Rodion (admin)     2022-09-29 12:42:23
User avatar

yep, I believe the problem supposed there could be some naive optimization - either caching, or some precalculation - but limit is not strong so even straightforward solution may be sufficient (if it satisfies curiosity of the author).

gardengnome     2022-09-29 13:28:57
User avatar

I tried some simple caching, and the speed-up was about 60%. Nice, but not an order of magnitude better and thus I preferred the simple straightforward solution.

sam_bandara     2022-09-30 05:00:01

Thanks guys, I try to go with PyPy. And let you know the outcome. Cheers, Sam.

sam_bandara     2022-10-12 01:15:04

Finaly, PyPy works guys, super fast. Cpython took 85.3S and PyPy just only 7.8S. Thanks!!

Gad     2023-02-07 19:11:24

less radical but still enough is using the numba module

Please login and solve 5 problems to be able to post at forum