# Euler Problem 11: Largest Product in a Grid

[This article was first published on

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

**The Devil is in the Data**, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

## Euler Problem 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 = 1,788,696. What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20 by 20 grid?

## Solution

The solution applies straightforward vector arithmetic. 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.

#Read and convert data square <- readLines("Euler/p011_matrix.txt") square <- as.numeric(unlist(lapply(square, function(x){strsplit(x, " ")}))) square <- matrix(square, ncol=20) # Define products 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)

The post Euler Problem 11: Largest Product in a Grid appeared first on The Devil is in the Data.

To

**leave a comment**for the author, please follow the link and comment on their blog:**The Devil is in the Data**.R-bloggers.com offers

**daily e-mail updates**about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.