Message Boards Message Boards

1
|
8929 Views
|
4 Replies
|
1 Total Likes
View groups...
Share
Share this post:

Why am I getting the word Return in the output?

Posted 12 years ago
I wrote the following code:
ptable = Map[(3 #^2 - #)/2 &, Range@4500];

For[k = 2250, k > 1, k--, atk = ptable[[k]];
  For[j = k - 1, j >= 1, j--, atj = ptable[[j]];
   If[MemberQ[ptable, atk - atj] && MemberQ[ptable, atk + atj], Return[atk - atj]]]] // Timing

I'm getting the following:
{34.491821, Return[5482660]}

Instead of what I expected:
{34.491821, 5482660}

Why?

thanks,
-Joe
POSTED BY: Joe Gilray
4 Replies
The following code is faster, and in your PC much faster than mine...

In my Pc, i get: boo // Timing, = {33.633816, 5482660}.

But with:

JesusCA =
Compile[{{kk, _Integer}},
Module[{}, ptable = Map[(3 #^2 - #)/2 &, Range@4500];
k = kk; out = 0; While[And[k > 1, out == 0],
atk = ptable[];
Do[atj = ptable[];
If[MemberQ[ptable, atk - atj] && MemberQ[ptable, atk + atj],
out = atk - atj;]
, {j, k - 1, 1, -1}]; k--]; out
], RuntimeAttributes -> {Listable}, Parallelization -> True];

JesusCA[2250] // Timing
 
{24.866559, 5482660}

My pc is slower than yours, but my code in faster. Bye.
Posted 12 years ago
Thanks for the help... I'm still learning some of the basics it seems!
POSTED BY: Joe Gilray
 boo := Module[{},
   ptable = Map[(3 #^2 - #)/2 &, Range@4500];
   For[k = 2250, k > 1, k--,
    atk = ptable[[k]];
    For[j = k - 1, j >= 1, j--,
     atj = ptable[[j]];
     If[MemberQ[ptable, atk - atj] && MemberQ[ptable, atk + atj],
      Return[atk - atj, Module]]
     ]
   ]
  ]
Now
boo // Timing
{22.401744, 5482660}
POSTED BY: Nasser M. Abbasi
Return is only use for functions, not for For-loops, you simply remove 'Return[]' for the case of a For-loop, it will return atk - atj.
POSTED BY: Sander Huisman
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract