user1613119
user1613119

Reputation: 235

Why do I get different answers for these two algorithms in 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.

Upvotes: 0

Views: 432

Answers (3)

Alex Brandt
Alex Brandt

Reputation: 99

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.

Upvotes: 1

paxdiablo
paxdiablo

Reputation: 881103

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).

Upvotes: 6

Blender
Blender

Reputation: 298056

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.

Upvotes: 1

Related Questions