Stanislaw Ulam once observed that if the counting numbers are arranged in a spiral, the prime numbers contained in it form a surprising pattern. They appear to cluster along diagonals of the spiral matrix.
Given n, return the length of the longest diagonal sequence of primes in spiral(n).
Example:
Input n = 7 Output d = 4
Since isprime(spiral(n)) is
1 0 0 0 1 0 0 0 0 0 1 0 0 0 1 0 1 0 0 0 0 0 1 0 0 1 1 0 0 0 1 0 1 0 1 0 1 0 0 0 1 0 1 0 0 0 0 0 1
I agree that the solution is mis-coded. isprime(spiral(4)) gives:
1 0 0 0
0 0 1 1
1 0 1 0
0 0 0 1
which means that d=2 for this case.
Rescoring based on corrected test suite. Sorry about that.
"find the longest diagonal arrangement of primes in spiral(n)" leaves room for misinterpretation.
I would have quickly understood:
"return the length of the longest diagonal sequence of primes in spiral(n)"
Like Jonathan Campelli, I still feel the problem statement could be clearer. From the example I eventually figure that reference is being made to the diagonally oriented elements running between elements (1,5) and (4,2) of isprime(spiral(n)). But arguably these are not on a/the "diagonal" of that matrix, per http://mathworld.wolfram.com/Diagonal.html (cf. https://en.wikipedia.org/wiki/Main_diagonal ).
Furthermore, there is no mention in the current online MATLAB documentation that "spiral" is actually a function that is already provided with MATLAB — i.e. that the user does not have to write their own function to make the spiral matrix. Apparently, "spiral can be found in the demo folder" [ref: https://stackoverflow.com/questions/29466058/spiral-loop-on-a-matrix-from-a-point].
hard
Interesting! This error stems from using "Ix" in both function and sub-function. As I test my code in scripts not contained within a function I was missing it.
Why are parameters made available to sub-functions by default?
this is really awesome and impressive.I do learn something
n = isprime(spiral(n))
thank you very much
a good precise algorithm
Best solution that doesn't cheat with a lookup or regexp
max(diff(find(~zeroOneVector)))-1 returns the longest run of ones in a vector of zeros and ones, but it FAILS IN SEVERAL CASES, e.g.:
- all ones: [1 1 1 1 1] returns empty
- just a single zero: [1 1 0 1 1] returns empty
- all zeros at one end: [1 1 1 0 0] returns 0
- longest run at one end: [1 1 0 1 0] returns the longest run between zeros, here 1
As a workaround for all cases, add zeros to both ends of the vector:
max(diff(find(~[0 zeroOneVector 0])))-1
However, this is not necessary for this solution because the matrix is very sparse.
Solve the set of simultaneous linear equations
174 Solvers
345 Solvers
145 Solvers
402 Solvers
1245 Solvers