Euler Project #1 in R

for-loop, r, while-loop

Solution

First, your loop runs until `i < 100`, not `i < 1000`.

Second, replace `x[i] <- c(x, i)` with `x <- c(x, i)` to add an element to the vector.

Problem

Problem Find the sum of all numbers below 1000 that can be divisible by 3 or 5 One solution I created: ``` x <- c(1:999) values <- x[x %% 3 == 0 | x %% 5 == 0] sum(values ``` Second solution I can't get to work and need help with. I've pasted it below. I'm trying to use a loop (here, I use while() and after this I'll try for()). I am still struggling with keeping references to indexes (locations in a vector) separate from values/observations within vectors. Loops seem to make it more challenging for me to distinguish the two. Why does this not produce the answer to Euler #1? ``` x <- 0 i <- 1 while (i < 100) { if (i %% 3 == 0 | i %% 5 == 0) { x[i] <- c(x, i) } i <- i + 1 } sum(x) ``` And in words, line by line this is what I understand is happening: - x gets value 0 - i gets value 1 - while object i's value (not the index #) is < 1000 - if is divisible by 3 or 5 - add that number i to the vector x - add 1 to i in order (in order to keep the loop going to defined limit of 1e3 - sum all items in vector x I am guessing x[i] <- c(x, i) is not the right way to add an element to vector x. How do I fix this and what else is not accurate?

Original source