I have three versions to with Module and a simpler one without to compute the sum of primes. However it will only return a value of 1. Not sure what to do? I thought Return[j,Module] would do the trick. see Returning a value from a Module
using
SumPrime[8]
to call them.
SumPrime[n_] := Module[{x = n},
For[{i = 1, j = 1}, {i <= PrimePi[n], Return[j, Module]}, {Set[j, j + Prime[i]], i++}]
]
SumPrime[n_] := Module[{x = n},
For[{i = 1, j = 1}, {i <= PrimePi[n], Return[j, Module]}, {j = j + Prime[i], i++}]
]
SumPrime[n_] := For[{i = 1, j = 1}, {i <= PrimePi[n], Return[j]}, {j = j + Prime[i], i++}]
For
$\endgroup$Return
. AndFor
is not your friend (just search on this site aboutFor
to learn why). Your code can be written in a much cleaner way withDo
, if it can't be written with functional programming. If you want a chunk of code that does exactly what you want here, but is faster and more readable, this will do it (assuming I got the gist of what you wanted to do):sumPrime[n_] := Total[Table[Prime[i], {i, PrimePi[n]}]]
$\endgroup$i=1;j=1
This is called a Compound Expression reference.wolfram.com/language/ref/CompoundExpression.html. $\endgroup$