1
$\begingroup$

This is what I have done to turn the string to executable code.

st = "prime[m_]:=Module[{i=2},\[IndentingNewLine]For[,i<m,i++,If[Mod[\
m,i]\[Equal]0,Print[ToString@m<>" is not a Prime "];Break[]]];\
\[IndentingNewLine]If[i\[Equal]m,Print[ToString@m<>" is a Prime "]]\
\[IndentingNewLine]]"
ToExpression[st]
prime[29]
prime[30]

enter image description here However, no success.

$\endgroup$
2
$\begingroup$

You need to escape the internal quotation marks like so:

st = "prime[m_]:=Module[{i=2},\[IndentingNewLine]For[,i<m,i++,If[Mod[\
m,i]\[Equal]0,Print[ToString@m<>\" is not a Prime \"];Break[]]];\
\[IndentingNewLine]If[i\[Equal]m,Print[ToString@m<>\" is a Prime \"]]\
\[IndentingNewLine]]";
ToExpression[st]
prime[29]
prime[30]

29 is a Prime 

30 is not a Prime 
$\endgroup$
2
  • $\begingroup$ There is a warning when I copied your code. Warning: comma encountered with no adjacent expression. The expression will be treated as Null. $\endgroup$ – kile Nov 12 '20 at 4:39
  • $\begingroup$ @kile That comes from your code. Namely, For[,i<m..... $\endgroup$ – Tim Laska Nov 12 '20 at 4:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.