sum of multiples of 3 from 0 to 100

10 ビュー (過去 30 日間)
Mina
Mina 2021 年 6 月 4 日
コメント済み: Walter Roberson 2021 年 6 月 5 日
Calculate the sum of all the multiples of 3 from 0 to 100 without using an if construct or vectorization.
I'm not sure how to do it without using an if construct.
sum = 0;
for x = 0:100
if mod(x,3) == 0
sum = sum + x;
end
end
fprintf ('The sum is %4d \n', sum);
  1 件のコメント
David Fletcher
David Fletcher 2021 年 6 月 4 日
編集済み: David Fletcher 2021 年 6 月 4 日
You're using an if construct - the only reason you need an if construct is to filter out the numbers that you don't need. So, don't generate the useless numbers in the first place.
As a hint - you can use a step size when writing this: for x = 0:100

サインインしてコメントする。

回答 (3 件)

Rik
Rik 2021 年 6 月 5 日
If I was your teacher I would just tell you to use a loop, leaving you to decide what you aren't allowed to do.
In this case you need to read the documentation for the colon function. It will tell you how you can introduce a step size.
doc colon
You should also avoid the use of sum as a variable name, as you are likely to use the sum function elsewhere in your code. If it already is a variable, that will cause strange issues.
  1 件のコメント
Walter Roberson
Walter Roberson 2021 年 6 月 5 日
I think the colon would count as vectorization.
It is then questionable whether using a colon in a for counts as vectorization. The model MATLAB uses is as if the limit expression was evaluated and all of the terms were stored ahead of time, but there is evidence that the implementation does not do that in the case of using a colon range.

サインインしてコメントする。


Manas Minnoor
Manas Minnoor 2021 年 6 月 5 日
編集済み: Manas Minnoor 2021 年 6 月 5 日
Hey Mina,
You can generate only the multiples of 3 in the for loop using the colon operator.
Please refer to the following documentation to view the different ways to utilize a for loop:
Hope this helps.
  1 件のコメント
Rik
Rik 2021 年 6 月 5 日
Please refrain from posting complete solutions to homework questions. That only encourages cheating.

サインインしてコメントする。


Walter Roberson
Walter Roberson 2021 年 6 月 5 日
s = 0;
for x = 0 : 100
s = s + (mod(x,3) == 0).*x;
end
s
s = 1683
sum(0:3:100)
ans = 1683
  2 件のコメント
Rik
Rik 2021 年 6 月 5 日
If colon is vectorization, then you should probably replace this with a while loop.
Walter Roberson
Walter Roberson 2021 年 6 月 5 日
Does a while loop count as an if statement ?

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by