Solutions to Project Euler 11: Greatest product of four adjacent numbers in the same direction (up, down left, right) in a 20×20 grid?

Project Euler 11: Largest product in a grid

Peter Prevos

Peter Prevos |

217 words | 2 minutes

Share this content

Project Euler 11 is a relatively straightforward application of vector arithmetics in R. Just like problem 8, it asks for the largest product.

Project Euler 11 Definition

In the 20×20 grid below, four numbers along a diagonal line have been marked in red. The product of these numbers is 26 × 63 × 78 × 14 = 1788696.

What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid?

Project Euler problem 11
Project Euler 11.

Solution

The solution applies straightforward vector arithmetic to multiply the verticals, horizontals and diagonals. The product of all verticals is an array of the product of rows 1 to 4, rows 2 to 5 and so on. The code uses a similar logic for the horizontals and the diagonals.

  ## Project Euler 11: Largest product in a grid

  square <- as.matrix(read.delim("data/p011_matrix.txt", header = FALSE, sep = " "))

  prod.vert <- square[1:17, ] * square[2:18, ] * square[3:19, ] * square[4:20, ]
  prod.hori <- square[ ,1:17] * square[ ,2:18] * square[ ,3:19] * square[ ,4:20]
  prod.dia1 <- square[1:17, 1:17] * square[2:18, 2:18] * square[3:19, 3:19] * square[4:20, 4:20]
  prod.dia2 <- square[4:20, 1:17] * square[3:19, 2:18] * square[2:18, 3:19] * square[1:17, 4:20]

  answer <- max(prod.vert, prod.hori, prod.dia1, prod.dia2)
  print(answer)

Share this content

You might also enjoy reading these articles

Project Euler 35: Circular Primes below One Million

Project Euler 144: Laser Beams and Elliptical Billiards

Project Euler 33: Digit Cancelling Fractions