Project Euler in R Problem 8

Problem 8 of Project Euler asks us to find the greatest product of five consecutive digits of a 1000 digit number. The problem and 1000 digit number can be found here.

I first saved the number in a text file and used the scan function to import the number into R. At first it is a 20 string characteric because “scan” separates items based on line breaks. The paste function then allows me to to concatenate the strings into one character. After that, I use the string split function to separate each number in the character into its own position in a vector. Finally, I convert the “strings” vector into a numeric vector so we can use mathematical operations on it.

It was easy to see that if we are taking products of 5 consecutive integers of a certain number, there are a total of x - 4 total products, where x is the total number of digits in the number. (If its a 5 digit number, only 1 product exist. For a 6 digit number, we can multiply 1 through 5 or 2 through 6 for 2 different products.)

Therefore, for this problem we had to consider 996 products. After allocating memory for an empty numeric vector, I ran a for loop 996 times to fill up the entries of the ‘products’ vector. The first entry became the product of the first 5 digits of our number, the second entry the product of digits 2-6, and so on.

1
2
3
4
5
6
7
8
9
10
11
12
13
string <- scan(file = "8.txt", what="")
string <- paste(string, collapse="")
string <- unlist(strsplit(string, split=""))
string <- as.numeric(string)

products <- numeric()

for (i in 1:996) {
products[i] <- (string[i] * string[i + 1] * string[i + 2]
              * string[i + 3] * string[i + 4])
}

max(products)

The for loop terminates very quickly and we can use a simple max(products) command to get our answer.