Sum of all the prime numbers under 100, sum of the ten smallest prime numbers.

7 ビュー (過去 30 日間)
Andreas Larsson
Andreas Larsson 2016 年 2 月 4 日
編集済み: Elias Gule 2016 年 5 月 13 日
As the title says i have to create a program which sums all the prime numbers under 100, and sums the ten smallest prime numbers. I can't use the built in functions like: sum, prime, etc. I tried making a program using those functions and it worked.
I'm thinking about something like this:
i have to write a program that detects a prime number, since a prime number only can be divided by 1 and itself, i need to write a program that detects that.
Then i need to customize it so that it detects all the prime numbers under 100.
Then it needs to sum all of the prime numbers under 100 and displays the "sum".
For the "ten smallest prime numbers", i have no idea to be honest..
Cheers!

採用された回答

Torsten
Torsten 2016 年 2 月 5 日
Oh come on ...
summe = 0;
nprime = 0;
for i = 2:100
istprime = 1;
for j = 2:i-1
if mod(i,j)==0
istprime = 0;
break;
end
end
if istprime == 1
nprime = nprime + 1;
summe = summe + i;
if nprime == 10
summe_first_ten = summe ;
end
end
end
Best wishes
Torsten.

その他の回答 (3 件)

Walter Roberson
Walter Roberson 2016 年 2 月 4 日
For the 10 smallest prime numbers, check whether 1 is prime, check whether 2 is prime, check whether 3 is prime, and so on, continuing until you have 10 prime numbers. A while loop.
Hint: if you have already found all the primes under 100, then you do not need to repeat that work; for example if it turns out there are 7 primes under 100 then you could continue on from 100 until you found as many more as you needed.
  4 件のコメント
Torsten
Torsten 2016 年 2 月 5 日
A very primitive approach to test whether a number "n" is prime or not is to use MATLAB's "mod" function. If mod(n,i) == 0 for some 2<=i<=n-1, n is not prime.
Best wishes
Torsten.
Andreas Larsson
Andreas Larsson 2016 年 2 月 5 日
this is how far i've come:
for i=2:100
for j=2:100
if(~mod(i,j))
break; % if factor found, not prime
end
end
if(j > (i/j))
fprintf('%d is prime\n', i);
end
end
Now i just need to sum them all together, i can't use sum function.

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


Torsten
Torsten 2016 年 2 月 5 日
summe = 0;
for i = 2:100
istprime = 1;
for j = 2:i-1
if mod(i,j)==0
istprime = 0;
break;
end
end
if istprime == 1
summe = summe + i;
end
end
Best wishes
Torsten.
  1 件のコメント
Andreas Larsson
Andreas Larsson 2016 年 2 月 5 日
Thank you!!
However, how should i do it, for it to calculate the sum of the 10 first prime numbers?

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


Elias Gule
Elias Gule 2016 年 5 月 12 日
編集済み: Elias Gule 2016 年 5 月 13 日
Does this help
primes_ = primes(100);
sum_ = sum(primes_(1:10));

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by