On a tangential note, there are faster ways of doing this.
If you are not comfortable with the math, yourself, you might use oeis
with some example values and find https://oeis.org/A000330 which
suggests F=: 3 :'y*(1+y)*(1+2*y)%6'
Is that an adequate solution?
F i.10
0 1 5 14 30 55 91 140 204 285
(+/@:([:*:1+i.))"0 (i.10)
0 1 5 14 30 55 91 140 204 285
(3) 6!:2 'F i.9999'
0.000323
F 9998
3.33183e11
x:F 9998
333183354999
(+/@:([:*:1+i.)) 9998
333183354999
Seems to be ok, and quick.
But, of course, that implementation floating point, which limits the
range of values it can handle. And we are fast enough that we can
switch to arbitrary precision integer arithmetic and still be faster
than the brute force approach:
(3) 6!:2 'F x:i.9999'
0.042063
I hope this helps...
Thanks,
--
Raul
On Wed, Jun 22, 2016 at 8:10 PM, Moon S <[email protected]> wrote:
> I was searching integer solutions (k,m) for
> 1^2 + 2^2 + ... + k^2 = m^2
> and I found that one expression runs much faster than the other:
>
> (#~(0=1|[:%:+/@:([:*:1+i.))"0) 2+i.9999
> 24
> (#~(0=1|[:%:+/@:(*:&>:&i.))"0) 2+i.9999
> 24
>
> The first one is ~100 times faster, and moreover, the expression with '+/'
> is faster, then without it!
>
> (3) 6!:2 '(+/@:([:*:1+i.))"0 (i.9999)' NB. with +/ and fork
> 0.143744
> (3) 6!:2 '(+/@:(*:&>:&i.))"0 (i.9999)' NB. with +/ and train
> 13.4614
>
> (3) 6!:2 '([:*:1+i.)"0 (i.9999)' NB. without +/
> 0.608895
> (3) 6!:2 '(*:&>:&i.)"0 (i.9999)'
> 14.0192
>
> As for '+/' I think the explanation is that no additional arrays are
> created, the sums are just computed on the fly.
> But the question remains, why the (equivalent) fork is so much faster than
> the train?
>
> Hm, changing the long train to a shorter one with a fork helps:
> (3) 6!:2 '(*:&(1+i.))"0 (i.9999)'
> 0.62027
> So, what's the rule?
>
> ---
> Georgiy Pruss
> ----------------------------------------------------------------------
> For information about J forums see http://www.jsoftware.com/forums.htm
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm