Sum in R - Use a loop to calculate the sum of all numbers | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 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?

2nd Jan 2022, 8:04 PM
Longhua68
Longhua68  - avatar
7 Antworten
+ 5
You need an extra variabele to add every sum that passes your if statement. And only print that variable after the loop finishes.
2nd Jan 2022, 8:27 PM
Paul
Paul - avatar
+ 5
print(total)
3rd Jan 2022, 9:56 AM
Simba
Simba - avatar
+ 4
#try this sum <- 0 total <- 0 while (sum <= 1000) { if (sum %% 3 == 0) total <- total + sum sum <- sum +1 } print(total)
3rd Jan 2022, 2:56 AM
Simba
Simba - avatar
+ 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)
2nd Jan 2022, 8:41 PM
Steve Nova
Steve Nova - avatar
+ 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!
3rd Jan 2022, 9:48 AM
Longhua68
Longhua68  - avatar
+ 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?
2nd Jan 2022, 10:14 PM
Longhua68
Longhua68  - avatar
+ 1
sum <- 0 for (x in 1:1000) { if (x %% 3 == 0) { sum = sum + x } } print(sum)
15th May 2022, 3:41 PM
Rafael Ulises Cuello Saviñón
Rafael Ulises Cuello Saviñón - avatar