Need to find the smallest [n] such that the sum for a harmonic series is greater than some value X.

조회 수: 2 (최근 30일)
I am new to programming/MATLAB and I know the attached code is incorrect, but I am lost. My goal is to find the smallest n-value such that the sum for a harmonic series is greater than some integer value (say 10). However, when I print [n], I just get the defined n value in the first line of code. I have commented my code to reflect my understanding. Please call me out when needed.
n = 200; %max number of rows that will print
S = 0; %initial starting value of sum
for i = 1:n %for the rows 1 to n (i.e. 200 rows)
S = S + 1/i; %apply this fn. to each element
if S >= 10 %if the sum (S) is greater than 10
break %the loop "breaks" (i.e. stops applying the fn.)
end %ends the break
end %ends the loop from row 1 to 200
n

채택된 답변

Walter Roberson
Walter Roberson 2021년 4월 14일
n = 25000; %max number of rows that will print
S = 0; %initial starting value of sum
for i = 1:n %for the rows 1 to n (i.e. 200 rows)
S = S + 1/i; %apply this fn. to each element
if S >= 10 %if the sum (S) is greater than 10
break %the loop "breaks" (i.e. stops applying the fn.)
end %ends the break
end %ends the loop from row 1 to 200
i
i = 12367
S
S = 10.0000
  댓글 수: 1
Edna1
Edna1 2021년 4월 14일
Thank you so much! I was very close then apparently. I tried printing [i] previously, but it looks like when the n-range is not large enough, it just returns the limit of the variable (until guessing the sufficient range limit).
Thanks again!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by