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

2 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Walter Roberson
Walter Roberson el 14 de Abr. de 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 comentario
Edna1
Edna1 el 14 de Abr. de 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!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by