# Trouble returning value from a function

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++}]

• check the syntax for For Dec 21, 2017 at 15:14
• Mathematica is not python. You don't need an explicit Return. And For is not your friend (just search on this site about For to learn why). Your code can be written in a much cleaner way with Do, 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]}]] Dec 21, 2017 at 15:16
• @ b3m2a1 thanks, I need to develop it further so I also want to subtract off each prime number and take the log so I need to manipulate each prime...Looking up Table[]. Dec 21, 2017 at 15:27
• @b3m2a1 yes seems that will work thanks again. Dec 21, 2017 at 15:32
• if you just want to evaluate things as a group use semicolons and no parenthesis. i=1;j=1 This is called a Compound Expression reference.wolfram.com/language/ref/CompoundExpression.html. Dec 21, 2017 at 15:59

You For-loop is ill-formed; it does not follow the syntax rules for Mathematica's For.

This will work.

sumPrime[n_] :=
Module[{i, j},
For[i = 1; j = 0, i <= PrimePi[n], i++, j += Prime[i]];
j]


10

Note that there is no need to use Return because Module automatically returns the result of evaluation its body (its 2nd argument), which is j. However, I recommend

sumPrime[n_] := Total @ Table[Prime[i], {i, PrimePi[n]}]


which is both simpler and quicker.

sumPrime[5]


10

Rather than iterative looping you can take advantage of the Listable attribute of many built-in functions:

sumPrime[n_] :=Total@Prime[Range[PrimePi[n]]]

• I think you need PrimePi in there: Total@Prime@Range@PrimePi@n Dec 22, 2017 at 17:26
• @george2079 correct. thanks. rushed it. was wanting to show listability rather than looping Dec 22, 2017 at 22:43
• Good on showing the listability. Might be good to make a quick note of it though in the body text. The OP seems like they know very little about how Mathematica works as a language. Dec 22, 2017 at 22:59