Summation of all odd numbers from 1 to 451

35 ビュー (過去 30 日間)
Zacharia
Zacharia 2022 年 8 月 19 日
コメント済み: Voss 2022 年 8 月 19 日
The following lines accurately sum when d (common difference) is 1, however, as soon as it changes, I get a wrong answer, does anyone understand why? I assume I am quite ignorant, but I would love any help I can get:
% Initialize n, a, d and s
n = 451;
a = 1;
d = 2;
S = 0;
% Compute S by adding the terms
for i = 1:n
S = S+a+(i-1)*d;
end
%Call S
S
Command Window:
S = 203401
  • Where S should actually equal: 51,076

回答 (2 件)

VBBV
VBBV 2022 年 8 月 19 日
編集済み: VBBV 2022 年 8 月 19 日
n = 451;
a = 1;
d = 2;
S = 0;
% Compute S by adding the terms
for i = 1:n
S(i) = (a+(i-1)*d/2);
end
sum(S(1:2:end)) % sum of all odd numbers
ans = 51076
  1 件のコメント
Zacharia
Zacharia 2022 年 8 月 19 日
Thankyou so much, I understand more from both answers now!
I truly appreciate your help, have a lovely day :)

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


Voss
Voss 2022 年 8 月 19 日
The for loop iterates n times, so after it's done, S represents the sum of n terms, which is fine when d = 1, but when d > 1, the summation you want has less than n terms.
In other words, there are 451 integers between 1 and 451 (inclusive), but only (451+1)/2 = 226 odd integers in that range and only (451+2)/3 = 151 integers congruent to 1 mod 3 (i.e., 1, 4, 7, 10, ...) in that range.
So "for i = 1:n" must be modified to take into account the value of d, so that the loop iterates the correct number of times.
  2 件のコメント
Zacharia
Zacharia 2022 年 8 月 19 日
That perfectly explains why it only worked for d = 1, I see now.
Thankyou so much for taking time out of you day to explain it, truly helped me
Voss
Voss 2022 年 8 月 19 日
You're welcome!

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

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by