+ 2
Sum in R - Use a loop to calculate the sum of all numbers
Sum Use a loop to calculate the sum of all numbers that are a multiple of 3 in the range of 1 to 1000. A number is a multiple of 3 if the remainder of dividing it by 3 is 0. sum = 0 while (sum < 1000) { if (sum %% 3 == 0) print (sum(sum)) sum = sum +1 } I have created the loop but I cannot figure out how to sum the values. Can you help?
7 Réponses
+ 5
You need an extra variabele to add every sum that passes your if statement. And only print that variable after the loop finishes.
+ 5
print(total)
+ 4
#try this
sum <- 0
total <- 0
while (sum <= 1000) {
if (sum %% 3 == 0)
total <- total + sum
sum <- sum +1
}
print(total)
+ 3
Try it in this way:
1st check if 3%%X == 0, then add it to some value Y. Loop 1000 times.
sum <- 0
for (x in 1:1000) {
if (x%%3 == 0) {
sum <- sum+x
}
print(sum)
+ 2
Thank you all!
sum <- 0
total <- 0
while (sum <= 1000) {
if (sum %% 3 == 0)
total <- total + sum
sum <- sum +1
}
print(sum)
this is still not solving the problem becouse it sums the number of lines of code not their value!
+ 1
Hi thank you all for the help. However it is not working and I do not have any clue of how to solve the problem ... any other idea?
+ 1
sum <- 0
for (x in 1:1000) {
if (x %% 3 == 0) {
sum = sum + x
}
}
print(sum)