MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn moreOpportunities for recent engineering grads.

Apply TodayStanislaw 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, find the longest diagonal arrangement 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

173 correct solutions
157 incorrect solutions

Last solution submitted on Jan 13, 2015

2 players like this problem

1 Comment

Jon
on 21 Mar 2014

Best solution that doesn't cheat with a lookup or regexp

1 Comment

Dirk Engel
on 26 Jun 2012

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.

2 Comments