Why do I get different answers for these two algorithms in R? - r

This is quite literally the first problem in Project Euler. I created these two algorithms to solve it, but they each yield different answers. Basically, the job is to write a program that sums all the products of 3 and 5 that are under 1000.
Here is the correct one:
divisors<-0
for (i in 1:999){
if ((i %% 3 == 0) || (i %% 5 == 0)){
divisors <- divisors+i
}
}
The answer it yields is 233168
Here is the wrong one:
divisors<-0
for (i in 1:999){
if (i %% 3 == 0){
divisors <- divisors + i
}
if (i %% 5 == 0){
divisors <- divisors + i
}
}
This gives the answer 266333
Can anyone tell me why these two give different answers? The first is correct, and obviously the simpler solution. But I want to know why the second one isn't correct.
EDIT: fudged the second answer on accident.

Because multiples of 15 will add i once in the first code sample and twice in the second code sample. Multiples of 15 are multiples of both 3 and 5.
To make them functionally identical, the second would have to be something like:
divisors<-0
for (i in 1:999) {
if (i %% 3 == 0) {
divisors <- divisors + i
} else {
if (i %% 5 == 0) {
divisors <- divisors + i
}
}
}
But, to be honest, your first sample seems far more logical to me.
As an aside (and moot now that you've edited it), I'm also guessing that your second output value of 26633 is a typo. Unless R wraps integers around at some point, I'd expect it to be more than the first example (such as the value 266333 which I get from a similar C program, so I'm assuming you accidentally left of a 3).

I don't know R very well, but right off the bat, I see a potential problem.
In your first code block, the if statement is true if either of the conditions are true. Your second block runs the if statement twice if both conditions are met.
Consider the number 15. In your first code block, the if statement will trigger once, but in the second, both if statements will trigger, which is probably not what you want.

I can tell you exactly why that's incorrect, conceptually.
Take the summation of all integers to 333 and multiply is by 3, you'll get x
Take the summation of all integers to 200 and multiply it by 5, you'll get y
Take the summation of all integers to 66 and multiply it by 15, you'll get z
x + y = 266333
x + y - z = 233168
15 is divisible by both 3 and 5. You've counted all multiples of 15 twice.

Related

R stops working and arrows disappearing with prime check function

prime <- function(number){
if (number!=2){
for (num in 1:number){
while ((number%%num)==0){
counter <- 0
counter <- counter+1
}
}
return((counter-2)==0)
}else{
FALSE
}
}
My function was designed for prime test, prime numbers only divided by itself and 1. So I've looped all the numbers from 1 to n(number itself) and counted the number of the 0 remainder divisions. Result must be 2 (n/n and n/1 remainders are 0) so (counter-2)==0 returns TRUE if the number is the prime number. Only exception is 2. But my code doesn't working also stops the RStudio. Code line arrows disappearing, R stops return any value.
What is wrong with this code?
I don't think you need a loop for this. Also, I'm not sure what you mean by the line arrow disappears, but this code works for me:
is.prime <- function(x){
if( x == 2) return(TRUE)
sum(x %% 1:x == 0) == 2
}
is.prime(2)
#> [1] TRUE
is.prime(10)
#> [1] FALSE
is.prime(11)
#> [1] TRUE
There are at least 3 problems with your code:
You are arbitrarily defining 2 as being non-prime. It is prime and there is no reason to treat it as a special case.
You are constantly resetting counter to 0. It should be initialized just once outside of the for loop
Your while loop is an infinite loop. If (number%%num)==0 then nothing in the body of the loop will make that false. This causes the loop to be an infinite loop, which is why RStudio hangs when you run your code. The fix is to change this loop into something which is not a loop at all -- it is really an if statement that you need.
There was another thing which isn't incorrect but is somewhat awkward: using (counter - 2) == 0 to test if counter == 2.
Fixing these problems leads to the following code:
prime <- function(number) {
counter <- 0
for (num in 1:number) {
if ((number %% num) == 0) {
counter <- counter + 1
}
}
counter == 2
}
This succeeds in correctly testing for primes. Note that it is an extremely inefficient test. Your test would use 1,000,000 remainder operations to classify 1,000,000 as nonprime when surely one operation would suffice -- just divide by 2. To make it more efficient you could exploit the fact that a number is either prime or it is divisible by a number no bigger than its square root. For an odd number, you can test if it is prime by checking if it has an odd divisor less that or equal to its square root. This would allow you to check if a number in the vicinity of 1,000,000 is prime with at most 500 remainder operations rather than the 1,000,000 that your approach would use.

for and if cicle operations

Hi¡ I have a doubt and I hope someone can help me please, I have a dataframe in R and it makes a double cicle for and an if, the data frame has some values and then if the condition is True, it makes some operations, the problem is I can't understand neither the cicle and the operation the code makes under the condition.
I reply the code I have in a simpler one but the idea is the same. And if someone can explain me the whole operation please.
w<-c(2,5,4,3,5,6,8,2,4,6,8)
x<-c(2,5,6,7,1,1,4,9,8,8,2)
y<-c(2,5,6,3,2,4,5,6,7,3,5)
z<-c(2,5,4,5,6,3,2,5,6,4,6)
letras<-data.frame(w,x,y,z)
l=1
o=1
v=nrow(letras)
letras$op1<-c(1)
letras$op2<-c(0)
for (l in 1:v) {
for (o in 1:v) {
if(letras$x[o]==letras$y[l] & letras$z[l]==letras$z[o] & letras$w[l]){
letras$op1<-letras$op1+1
letras$op2<-letras$x*letras$y
}
}
}
The result is the following:
Thanks¡¡¡¡¡
This segment of code is storing values into vectors labeled w,x,y,z.
w<-c(2,5,4,3,5,6,8,2,4,6,8)
x<-c(2,5,6,7,1,1,4,9,8,8,2)
y<-c(2,5,6,3,2,4,5,6,7,3,5)
z<-c(2,5,4,5,6,3,2,5,6,4,6)
It then transforms the 4 vectors into a data frame
letras<-data.frame(w,x,y,z)
This bit of code isn't doing anything as far as I can tell.
l=1 #???
o=1 #???
This counts how many rows is in the letras data frame and stores to v, in this case 11 rows.
v=nrow(letras)
This creates new columns in letras dataframe with all ones in op1 and all zeros in op2
letras$op1<-c(1)
letras$op2<-c(0)
Here each for loop is acting as a counter, and will run the code beneath it iteratively from 1 to v (11), so 11 iterations. Each iteration the value of l will increase by 1. So first iteration l = 1, second l=2... etc.
for (l in 1:v) {
You then have a second counter, which is running within the first counter. So this will iterate over 1 to 11, exactly the same way as above. But the difference is, this counter will need to complete it's 1 to 11 cycle before the top level counter can move onto the next number. So o will effectively cycle from 1 to 11, for each 1 count of 1l. So with the two together, the inside for loop will count from 1 to 11, 11 times.
for (o in 1:v) {
You then have a logical statement which will run the code beneath if the column x and column y values are the same. Remember they will be calling different index values so it could be 1st x value vs the 2nd y value. There is an AND statement so it also needs the two z position values to be equal. and the last part letras$w[l] is always true in this particular example, so could possibly be removed.
if(letras$x[o]==letras$y[l] & letras$z[l]==letras$z[o] & letras$w[l]){
Lastly, is the bit that happens if the above statement is true.
op1 get's 1 added (remember this was starting from 1 anyway), and op2 multiplies x*y columns together. This multiplication is perhaps a little bit inefficient, because x and y do not change, so the answer will calculate the same result each time the the if statement evaluates TRUE.
letras$op1<-letras$op1+1
letras$op2<-letras$x*letras$y
}
}
}
Hope this helps.

What is the R equivalence of Python's modulo (%) operator? [duplicate]

What is the double percent (%%) used for in R?
From using it, it looks as if it divides the number in front by the number in back of it as many times as it can and returns the left over value. Is that correct?
Out of curiosity, when would this be useful?
The "Arithmetic operators" help page (which you can get to via ?"%%") says
‘%%’ indicates ‘x mod y’
which is only helpful if you've done enough programming to know that this is referring to the modulo operation, i.e. integer-divide x by y and return the remainder. This is useful in many, many, many applications. For example (from #GavinSimpson in comments), %% is useful if you are running a loop and want to print some kind of progress indicator to the screen every nth iteration (e.g. use if (i %% 10 == 0) { #do something} to do something every 10th iteration).
Since %% also works for floating-point numbers in R, I've just dug up an example where if (any(wts %% 1 != 0)) is used to test where any of the wts values are non-integer.
The result of the %% operator is the REMAINDER of a division,
Eg. 75%%4 = 3
I noticed if the dividend is lower than the divisor, then R returns the same dividend value.
Eg. 4%%75 = 4
Cheers
%% in R return remainder
for example:
s=c(1,8,10,4,6)
d=c(3,5,8,9,2)
x=s%%d
x
[1] 1 3 2 4 0

How to use/understand "%%" [duplicate]

What is the double percent (%%) used for in R?
From using it, it looks as if it divides the number in front by the number in back of it as many times as it can and returns the left over value. Is that correct?
Out of curiosity, when would this be useful?
The "Arithmetic operators" help page (which you can get to via ?"%%") says
‘%%’ indicates ‘x mod y’
which is only helpful if you've done enough programming to know that this is referring to the modulo operation, i.e. integer-divide x by y and return the remainder. This is useful in many, many, many applications. For example (from #GavinSimpson in comments), %% is useful if you are running a loop and want to print some kind of progress indicator to the screen every nth iteration (e.g. use if (i %% 10 == 0) { #do something} to do something every 10th iteration).
Since %% also works for floating-point numbers in R, I've just dug up an example where if (any(wts %% 1 != 0)) is used to test where any of the wts values are non-integer.
The result of the %% operator is the REMAINDER of a division,
Eg. 75%%4 = 3
I noticed if the dividend is lower than the divisor, then R returns the same dividend value.
Eg. 4%%75 = 4
Cheers
%% in R return remainder
for example:
s=c(1,8,10,4,6)
d=c(3,5,8,9,2)
x=s%%d
x
[1] 1 3 2 4 0

What does the double percentage sign (%%) mean?

What is the double percent (%%) used for in R?
From using it, it looks as if it divides the number in front by the number in back of it as many times as it can and returns the left over value. Is that correct?
Out of curiosity, when would this be useful?
The "Arithmetic operators" help page (which you can get to via ?"%%") says
‘%%’ indicates ‘x mod y’
which is only helpful if you've done enough programming to know that this is referring to the modulo operation, i.e. integer-divide x by y and return the remainder. This is useful in many, many, many applications. For example (from #GavinSimpson in comments), %% is useful if you are running a loop and want to print some kind of progress indicator to the screen every nth iteration (e.g. use if (i %% 10 == 0) { #do something} to do something every 10th iteration).
Since %% also works for floating-point numbers in R, I've just dug up an example where if (any(wts %% 1 != 0)) is used to test where any of the wts values are non-integer.
The result of the %% operator is the REMAINDER of a division,
Eg. 75%%4 = 3
I noticed if the dividend is lower than the divisor, then R returns the same dividend value.
Eg. 4%%75 = 4
Cheers
%% in R return remainder
for example:
s=c(1,8,10,4,6)
d=c(3,5,8,9,2)
x=s%%d
x
[1] 1 3 2 4 0

Resources