问题
Here is two codes in Mathematica to give the sum of primes up to n or up to n-th prime.
ps2[n_]:= Sum[If[Element[p,Primes],p,0],{p,2,n}]
or
ps3[n_]:=Sum[1/Prime[i],{i,1,n}]
or
ps1[n_]:=Sum[If[Element[p,Primes],p,0],{p,2,n}]
or
ps[n_]:=Sum[Prime[i],{i,1,n}]
Now I am looking for some code to do these sums and plot that in MATLAB
, any idea?
Thanks.
回答1:
The first one is rather easy in Matlab:
function result = ps(n)
result = sum(primes(n))
(see PRIMES)
回答2:
Using primes
, as suggested by @Tobias Kienzler, you can write the sum of n primes as
sumPrimes = sum(primes(n));
The sum of the inverse of n primes is
sumInversePrimes = sum(1./primes(n));
Note that in Matlab, you don't usually write everything as a function; instead you calculate the results and manipulate them as arrays.
来源:https://stackoverflow.com/questions/5231555/sum-of-primes-and-reciprocals-of-them-and-plot-in-matlab