gilrays
(Joe Gilray)
1
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
sghuisman
(Sander Huisman)
2
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.
nma
(Nasser M. Abbasi)
3
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}
gilrays
(Joe Gilray)
4
Thanks for the help… I’m still learning some of the basics it seems!
cilleroares
(Jesús Manuel Cillero Ares)
5
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.