function n = one_per_n(x)
%Input x is a scalar
%Output n is a positive integer
%Example: n = one_per_n(4)
% n = 31
sum=0;
n=0;
while sum<x
if n<10000
n=n+1;
sum=sum+1/n;
else
n=-1;
return;
end
end
Search Program on this blog
Wednesday, 19 August 2015
Write a function called one_per_n that returns the smallest positive integer n for which the sum 1 + 1/2 + 1/3 + … + 1/n, is greater than or equal to x where the scalar x is the input argument. Limit the maximum number n of terms in the sum to 10,000 and return -1 if it is exceeded. (Note: if your program or the grader takes a long time, you may have created an infinite loop and need to hit Ctrl-‐C on your keyboard.)
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment