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

10 views (last 30 days)
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

Accepted Answer

Walter Roberson
Walter Roberson on 14 Apr 2021
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 Comment
Edna1
Edna1 on 14 Apr 2021
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!

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!