用R语言解Project Euler问题
用R语言解Project Euler问题(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.
这题很简朴,已经有高出20万的用户提交了正确谜底。题目要求的是1000以内3和5的倍数的和。
# 解法一:
x = 1:999
sum(x[x %% 3 == 0 | x %% 5 == 0])
# 解法二:
x = 1
sum = 0
while (x < 1000){
if (x %% 3 == 0 | x %% 5 == 0){
sum = sum + x
}
x = x + 1
}
print(sum)
# 解法三:本身写的,改用for轮回。
sum = 0
for (x in 1:999){
if (x %% 3 == 0 | x %% 5 == 0){
sum = sum + x
}
x = x + 1
}
print(sum)
# 解法四:结构一个计较x以内能被n整除的自然数的求和函数。
SumDiv = function(x, n){
p = floor(x / n)
n * p * (p + 1) / 2
}
sum = SumDiv(999, 3) + SumDiv(999, 5) – SumDiv(999, 15)
print(sum)
12345下一页