MATLAB: Finding the sum of the first n primes and to use a while function

n primessumwhilewhile loop

clear % This scripts attempts to find the sum of the first n primes
n=input('Enter a value for n');
i = 1;
prime_count=0;
sum = 0;
while prime_count <= n
if ~isprime(i)
% isprime returns TRUE if i is a prime
prime_count = prime_count + 1;
sum = sum + i;
end
i = i + 1;
end
fprintf('The sum of the first %d primes is %d\n', n, sum);

Best Answer

You stopped your while loop the wrong way. As it is, if you allow prime_count to be less than or EQUAL to n, then it adds ONE more prime into the sum. And that is one prime too many.
Next, NEVER use sum as a variable. If you do, then your next post here will be to ask in an anguished voice, why the function sum no longer works. Do not use existing function names as variable names.
The following code (based on yours) does now work:
n = 10;
i = 1;
prime_count=0;
psum = 0;
while prime_count < n
if isprime(i)
% isprime returns TRUE if i is a prime
prime_count = prime_count + 1;
psum = psum + i;
end
i = i + 1;
end
prime_count
prime_count = 10
psum
psum = 129
Does it agree?
plist = primes(1000);
sum(plist(1:10))
ans = 129
Of course.