I'm pretty new to programming in Mathematica and have a question. I wrote this function to factorise large numbers. The outputs are almost as expected, but I don't understand where the null's come from. How do I get rid of those? The first example should output 1229, the second should output nothing. Any help appreciated.

In[87]:= pollardrho[n_] := Module[{x, y, d},
x = 2;
y = 2;
d = 1;
g[x_] := Mod[x^2 + 1, n];
While[d == 1,
    x = g[x];
    y = g[g[y]];
    d = GCD[Abs[x - y], n];
If[d == n, , d]]

In[88]:= pollardrho[2896753]

Out[88]= 1229 Null

In[89]:= pollardrho[17]

Out[89]= Null^2
  • 1
    $\begingroup$ They're probably from the first part of th If which returns nothing. $\endgroup$ Feb 10 '15 at 12:16
  • $\begingroup$ How, though? I mean, only one of the two statements in the If part should be evaluated, did I go wrong somewhere? $\endgroup$
    – Snowflake
    Feb 10 '15 at 12:19
  • $\begingroup$ You have mis-matched parentheses. The If is inside the While loop, so gets evaluated more than once. $\endgroup$
    – bill s
    Feb 10 '15 at 13:56
  • 2
    $\begingroup$ It looks like you made a typo, maybe you forgot the semi-colon after the While loop. It's hard to be sure as the code you posted here is not the same as the code in your notebook (I can tell because the code here will not run at all due to missing brackets). $\endgroup$ Feb 10 '15 at 17:28

Although achieving the desired output requires only minor modifications to the Module, I provide it here in a modestly more compact form:

pollardrho[n_] := Module[{x = 2, y = 2, d = 1}, g[x_] := Mod[x^2 + 1, n]; 
  While[d == 1, x = g[x]; y = g[g[y]]; d = GCD[Abs[x - y], n]];
  If[d == n, "Null", d]]

(* 1229 *)

(* Null *)
  • 1
    $\begingroup$ pollardrho[17] is supposed to return Null though $\endgroup$ Feb 10 '15 at 17:29
  • $\begingroup$ Sorry for the misunderstanding on my part. I believe that the modified Modeule does the job. Note that I put Null in quotes, so that you could see it in the output. Otherwise, pollardrho[17] produces no visible output. $\endgroup$
    – bbgodfrey
    Feb 10 '15 at 22:26

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.