Several Cody problems (21, 69, 42937, 44448, 44784, 52422) involve Collatz sequences. These start with a seed n. If n is odd, the next element is
, and if n is even, the next element is
. For example, if the seed is 3, then the sequence is 3, 10, 5, 16, 8, 4, 2, 1. The Collatz conjecture is that all of these sequences terminate at the value 1; that is, all seeds lead to terminating sequences.
This problem deals with the number of primes in the sequence. With a seed of 3, the number of primes is 3 (2, 3, 5).
Write a function to determine the numbers of primes in the sequences with seeds of 1 to the input number. See the test suite for banned terms and commands.
Solution Stats
Problem Comments
5 Comments
Solution Comments
Show comments
Loading...
Problem Recent Solvers22
Suggested Problems
-
Omit columns averages from a matrix
620 Solvers
-
Back to basics 6 - Column Vector
1115 Solvers
-
Find third Side of a right triangle given hypotenuse and a side. No * - or other functions allowed
254 Solvers
-
836 Solvers
-
Mechanical Advantage of a Gear Train
474 Solvers
More from this Author330
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
I notice that p=isprime(x) can be a lot slower than p=ismember(x,primes(max(x))); for x=1:1e7, the former takes about 100 seconds and the latter takes about 0.1 seconds.
Nice observation. I'll keep that one in mind.
Actually for the first case (seed n = 1), the answer should be 1 and not 0, since the corresponding Collatz sequence is the loop (1, 4, 2), should'nt it be ?
Ok I suppose we don't count the special case of this infinite loop since we do have to stop the sequence at a point ! (1)
The speed difference noted by Tim was over five years ago, so I thought to test it again. (I presume he meant timing results for only the commands shown in his comment, rather than using either within his problem solution, as my solution worked much faster with isprime(x); perhaps this speedup is only present for very large vectors, while this problem requires looping over many small-to-medium-sized vectors.)
Given MATLAB has undergone performance improvements over the past years, I was able to run the two commands 10 times each for x = 1:1e7 using the Cody server.
The first version, using only one command (isprime), took 14.0911 seconds total (about 1.4 s/iteration) while the second, multi-function version took 0.7219 seconds total (about 0.07 s/iteration).
While the 1000x speedup he identified is no longer present, as all related functions seem to run faster, there is still a benefit to using his discovery for very large vectors; his alternate version is still almost 20 times faster.