Problem 2342. Numbers spiral diagonals (Part 2)
Inspired by Project Euler n°28 and 58.
A n x n spiral matrix is obtained by starting with the number 1 and moving to the right in a clockwise direction.
For example with n=5, the spiral matrix is :
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
The sum of the numbers on the diagonals is 101 (See problem 2340) and you have 5 primes (3, 5, 7, 13, 17) out of the 9 numbers lying along both diagonals. So the prime ratio is 5/9 ≈ 55%.
With a 7x7 spiral matrix, the ratio is 62% (8 primes out of the 13 diagonal numbers).
What is the side length (always odd and greater than 1) of the square spiral for which the ratio of primes along both diagonals FIRST falls below p% ? (0<p<1)
Solution Stats
Problem Comments
-
3 Comments
Christian Schröder
on 26 Sep 2022
Interesting problem! If I'm not mistaken, your description of the problem is not entirely accurate, however. For n = 1, the spiral matrix is just [ 1 ], for which the share of primes on the main diagonals is zero, below any given 0 < p < 1; so strictly speaking the correct answer to the problem as posed would be 1 for any p.
Dyuman Joshi
on 26 Sep 2022
Nice observation, @Christian!
I have edited the question statement, it (now) asks for an odd integer greater than 1.
Andrew
on 7 Apr 2025
This is a seriously good problem. Love it! You will have to optimize your code in order for the tests to not time out.
Solution Comments
Show commentsGroup

Introduction to MATLAB
- 23 Problems
- 8733 Finishers
- Add two numbers
- Find the sum of all the numbers of the input vector
- Maximum value in a matrix
- Return area of square
- Finding Perfect Squares
- Make the vector [1 2 3 4 5 6 7 8 9 10]
- Generate a vector like 1,2,2,3,3,3,4,4,4,4
- Triangle Numbers
- Length of the hypotenuse
- Select every other element of a vector
- Reverse the vector
- Column Removal
- Swap the input arguments
- Swap the first and last columns
- Check if number exists in vector
- Determine whether a vector is monotonically increasing
- Getting the indices from a vector
- Create times-tables
- Return the first and last characters of a character array
- Number of 1s in a binary string
- Make a random, non-repeating vector.
- Magic is simple (for beginners)
- Sum all integers from 1 to 2^n
Problem Recent Solvers160
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!