| This post was kindly contributed by 数据科学与R语言 - go there to comment and to read the full post. |
# Euler 6
x <- 1:100
sum(x)^2 - sum(x^2)
# Euler 7
n <- 0
i <- 1
m <- rep(0,10001)
while (n <10001) {
if (findprime(i)) {
n <- n +1
m[n] <- i}
i <- i + 1
}
m[10001]
# 预备练习,熟悉一些字符串操作函数
text <- c('hello','world','I','love','code')
gsub('o',' ',text)
gsub('o','*',text)
gsub('o','',text)
(temp1 <-paste(text,collapse=' '))
paste(text,collapse='*')
paste(text,collapse='')
(temp2 <- strsplit(temp1," "))
class(temp2)
(temp3 <- unlist(strsplit(temp1," ")))
class(temp3)
# Euler 8
web <- 'http://projecteuler.net/problem=8'
# 用readLines函数来抓取网页
raw <- readLines(web)
raw <- raw[54:73]
# 删除多余字符串
data <- gsub('<br />','',raw)
# 粘合成一个字符串
num <- paste(data,collapse='')
# 分割后转为数值向量
temp <- as.numeric(unlist(strsplit(num,'')))
p <- numeric()
for ( i in 1:(1000-4)) {
p[i] <- prod(temp[i:(i+4)])
}
max(p)
第六题用R的向量化计算非常简单,第七题需要用到第二题中建立的findprime函数。第八题的解决是用字符串方法,先将那一长串数字作为字符串切开,再转为数值型向量,最后用循环求乘积。为了偷懒,是直接抓取的网页,没有输入那个长长的数字。