sum of primes and reciprocals of them and plot in matlab?

血红的双手。 提交于 2019-12-11 17:55:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!