See my problem 42673: Longest Collatz Sequence
Brilliant. Power in simplicity. An order of magnitude faster than my attempt.
Thanks. Don't know why mod(a,m) is slower than a-floor(a/m)*m.
Probably internal input/output argument checks. Multiply it via millions of iterations and you get significant difference. Your algorithm saves tons of time (in comparison) because you didn't bother to store all the steps, therefore you didn't fell into "dynamic indexing" trap which saves some steps, but drastically slows down the process during saving values to the main array.
I guess this is one of those times where saving the intermediate steps doesn't help your computation time. Nicely done. As a comparison, using mod(b,2) takes about two-thirds longer than 2*floor(b/2) on my machine; 18.8 sec vs 11.3 sec for n=1e8, and 38 sec vs 23 sec for 2e8. That's good to know for speeding things up in other codes I need to run millions of times!
mod(b,k) takes about 10x longer than b-k*floor(b/k) on my machine (2016b win64):
a = randi(1e7,1e8,1); m = 37;
tic, b = mod(a,m); toc;
tic, c = a - floor(a/m)*m; toc;
norm(b - c)
Elapsed time is 3.131306 seconds.
Elapsed time is 0.253768 seconds.
I did the same thing, minus the uint64. My Project Euler code timed out on the 1e7 and 1e8 test cases.
That's right. My code would pass the test suite if last test were changed from 1e8 to 2e7, but that's all. 1e8 would take approx 110 seconds on Cody servers.
Column norms of a matrix
Back to basics 22 - Rotate a matrix
Solve the set of simultaneous linear equations
Given a matrix, return the last eigen value
Project Euler: Problem 18, Maximum path sum I
Project Euler: Problem 11, Largest product in a grid
Find the treasures in MATLAB Central and discover how the community can help you!
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list:
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Contact your local office