Categories
Coding Project Euler R

Project Euler Problem #10 (R)

Problem 10 asks us to find the sum of the prime numbers below 2*106. With the sieve() routine written for one of the earlier problems, this is easy: it becomes

> sum(sieve(2E6))

It is slow, however. It makes you appreciate how computationally intensive it is to search for larger primes.

Categories
Coding Project Euler R

Project Euler Problem #9 (R)

Problem 9 involves finding the Pythagorean triple \(a^2+b^2=c^2\) where a+b+c=1000.

Pythagorean triples have lots of useful relationships that we can exploit. The ones we shall use to solve this problem are:

\[a = k(m^2-n^2)\]

\[b = k(2mn)\]

\[ c = k(m^2+n^2) \]
In this case, we take \(k=1\), and generate the triples as follows:

# Problem 9
# Pythagorean Triple
problem9 <- function() {

        sum <- 0
        a <- 0; b <- 0; c <- 0;
        m <- 0

        for (m in 1:1000) {
         for (n in m:1000) {
         a <- m^2-n^2
         b <- 2*m*n
         c <- n^2 + m^2

         if (all(a^2 + b^2 == c^2, sum(a,b,c)==1000)) {
          return(prod(a,b,c))
         }
        }
        }
}

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
}