Categories
Coding Project Euler R

Project Euler Problem #8 (R)

Problem #8 on the Project Euler problem list requires finding the greatest product of five consecutive digits in a large string of integers.

For this problem, I copied and pasted the large number into a file, and read it in using scan(). As there were line breaks in the copied and pasted numbers, I used paste() with the collapse argument to restore it to a single line. From there, it was a matter of taking 5-character substrings, converting them to numbers, and using prod() to calculate the product of each group of 5 numbers.

gprod <- function() {
 # Read number as string
 snum <- scan(file="number.dat", what=character(0),
  strip.white=TRUE, quiet=TRUE)
 # Concatenate lines into a single line
 snum <- paste(snum, collapse="", sep="")
 mp <- 0
 for (i in 1:(nchar(snum)-4)) {
  s <- substr(snum, i, i+4)
  m <- prod(as.numeric(strsplit(s,"")[[1]]))
  if (m > mp) {
   mp <- m
}
 }
 mp
}