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

30 ビュー (過去 30 日間)
Samuel Walker
Samuel Walker 2021 年 3 月 7 日
編集済み: John D'Errico 2021 年 3 月 7 日
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);

採用された回答

John D'Errico
John D'Errico 2021 年 3 月 7 日
編集済み: John D'Errico 2021 年 3 月 7 日
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.

その他の回答 (2 件)

Matt J
Matt J 2021 年 3 月 7 日
if isprime(i)
  1 件のコメント
Samuel Walker
Samuel Walker 2021 年 3 月 7 日
i took away the ~ sign but the value is still off

サインインしてコメントする。


Jorg Woehl
Jorg Woehl 2021 年 3 月 7 日
編集済み: Jorg Woehl 2021 年 3 月 7 日
There are two issues in your code:
  1. You are testing if i is not a prime number, when you actually want to test whether it is a prime number, according to the statements that are executed in this case. Therefore, change ~isprime(i) to isprime(i).
  2. The while loop should continue until n prime numbers have been found. Yet your loop execution condition is prime_count <= n, which means that even if prime_count is equal to n the loop would continue to run until prime_count is n+1! Change prime_count <= n to prime_count < n and you are good to go.
Although your code will work as a script, it would be nicer to put it into a function where the user is directly supplying n as opposed to being asked to enter it during execution. It also avoids the need for a clear statement, as functions operate in their own variable space.
function sum = firstNPrimes(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
end

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by