1. If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
找到小于1000的 而且 是3或者5的倍数的 自然数,求它们的和。
x <- 1
sum <- 0
while (x < 1000) {
if (x%%3==0 | x%%5==0) {
sum <- sum + x
}
x <- x + 1
}
print(sum)
2. Each new term in the Fibonacci sequence(http://baike.baidu.com/view/1074762.htm) is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
有一个小于400万的斐波那契数列,求其中的偶数和。
i <- 2
x <- 1:2
while (x[i]<4000000) {
x[i+1] <- x[i-1]+x[i]
i <- i+1
}
sum(x[x%%2==0])
3. The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
求 600851475143的最大质数因子。findprime <- function(x) {
if (x %in% c(2,3,5,7)) return(TRUE)
if (x%%2 == 0 | x==1) return(FALSE)
xsqrt <- round(sqrt(x))
xseq <- seq(from=3,to=xsqrt,by=2)
if (all(x %% xseq !=0)) return(TRUE)
else return(FALSE)
}
# x = 1:111
# x[sapply(x,findprime)]
maxfactor <- 0
n <- 110
for (i in seq(from=3, to=round(sqrt(n))+1, by=2)) {
if (findprime(i) & (n %% i == 0)) {
#i是质数因子
n <- n / i
maxfactor <- i
if (i >= n) break
}
}
print(maxfactor)
参考文章求最大质因子的N种境界