Summing the multiples of 3 and 5 under 100

9 views (last 30 days)
So I'm writing a script that does as the title says
i= 1:99;
v1 = (rem(i,3) == 0);
v2 = (rem(i,5) == 0);
v3 = v1 + v2;
v4 = (v3 == 2);
v5 = v3 - v4;
v6 = v5.*i;
sum(v6)
The script does work. I just want to ask if you guys think this is a good script or is there a simpler way of writing the script by possibly using a loop or something?
  1 Comment
Image Analyst
Image Analyst on 28 Jun 2015
The question is ambiguous . Does it mean (1) find numbers that are multiples of both 3 and 5, and sum those, OR does it mean (2) find numbers that are multiples of either 3 or 5 and sum those? In the first case 9 would not be in the sum because it's not a multiple of both 3 and 5 (but only 3), and in the second case, 9 would be included because it's a multiple of 3 even though it's not also a multiple of 5.
If you cannot get a clear answer to the ambiguous wording then you might have to explain and do it both ways. You did case (2) while I did case (1) in my answer.

Sign in to comment.

Accepted Answer

Star Strider
Star Strider on 28 Jun 2015
You’re using vectorised code, much more efficient than a loop for what you are doing.
Doing all your essential vector manipulations with logical vectors, then assigning and summing them at the end, is certainly an interesting approach!
+1 for originality!

More Answers (3)

Venkatesh Ramaning
Venkatesh Ramaning on 19 Sep 2017
Edited: Venkatesh Ramaning on 19 Sep 2017
another method this will find the multiples of 3 and 5 and then sum all the unique values in 'x' here 'n' is any positive integer may be 100
a = 0:3:n;
b = 0:5:n;
c = [a,b];
x = sum(unique(c));

Image Analyst
Image Analyst on 28 Jun 2015
If you're looking for a more compact way, you might try this:
v = 5:5:99;
[ia, ib] = ismember(v, 3:3:99)
theSum = sum(v(ia))
If you really want a loop, we can do that too, just let us know. If you like the answer(s), you can also vote for it (them).

Mian  Arif
Mian Arif on 19 Nov 2016
Edited: Stephen23 on 19 Sep 2017
function a=sum3and5muls(n)
v=1:n;
c=find(rem(v,3)==0 | rem(v,5)==0);
a=sum(c);
end
I think this way is easier.
  2 Comments
Jan
Jan on 19 Nov 2016
Edited: Jan on 19 Nov 2016
@Mian Arif: Please use the "{} Code" button to make the code readable. Thanks.
I'd prefer:
v = 1:n;
a = sum(v(rem(v,3)==0 | rem(v,5)==0));
Stephen23
Stephen23 on 19 Sep 2017
@Mian Arif: the find is not required.

Sign in to comment.

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!