Reputation: 3
Even Fibonacci numbers sum whose values do not exceed four million. I am using multiline function in APL, but not getting the output:
result←Euler2 a;b;c;sum;i;limit
b←0
c←1
sum←0
i←0
limit←4000000
:For i :In limit
a←b
b←c
c←a+b
:If (0=2|c)
sum←(sum+c)
:EndIf
:EndFor
result←sum
Upvotes: 0
Views: 173
Reputation: 402
Warning: opinions below.
I would avoid using manual loops and tradfns. The resulting solution will (often) be clunky and slow. APL has powerful abilities for array processing, use them as much as you can.
Here's a different possible solution, using 'dfns'.
+/{⍵/⍨0=2|⍵}1↓{⍵,⍨+/2↑⍵}⍣{4000000<⊃⍺} 1 1
⍝ explanation:
{⍵,⍨+/2↑⍵} +/2↑⍵ the sum of the first two items in ⍵
⍵,⍨ prepend to ⍵
{⍵,⍨+/2↑⍵} 1 1 is 2 1 1
{⍵,⍨+/2↑⍵} 2 1 1 is 3 2 1 1
⍣ do this (see https://help.dyalog.com/18.0/Content/Language/Symbols/DieresisStar.htm)
{4000000<⊃⍺} 1 1 until the previous element (⊃⍺) is greater than 4 million, starting with the vector 1 1
'result:', {⍵,⍨+/2↑⍵}⍣{⎕←⍺⋄100<⊃⍺} 1 1
2 1 1
3 2 1 1
5 3 2 1 1
8 5 3 2 1 1
13 8 5 3 2 1 1
21 13 8 5 3 2 1 1
34 21 13 8 5 3 2 1 1
55 34 21 13 8 5 3 2 1 1
89 55 34 21 13 8 5 3 2 1 1
144 89 55 34 21 13 8 5 3 2 1 1
result: 144 89 55 34 21 13 8 5 3 2 1 1
1↓... remove the first element, as it is greater than 4 million
+/{⍵/⍨0=2|⍵} sum of the even numbers
Upvotes: 2
Reputation: 7616
The :For
construct takes a list of values after the :In
keyword. You're only giving it the limit. Maybe you meant ⍳limit
to give it all values from 1 until four million?
Upvotes: 1