1 min read

APL Hacking: Project Euler (#26)

Problem #26:

∇Z←CYCLE∆LENGTH N;A;I;R
⍝ Find the length of the cycle of 1÷N.
Z←0 ⋄ I←0 ⋄ A←N⍴0 ⋄ R←1
LP:I←I+1 ⋄ Z←I-A[R] ⋄ →(0≠A[R])/0
A[R]←I ⋄ R←N|R×10 ⋄ →(0=R)/Z←0
→LP
∇

∇Z←PETWENTYSIX
⍝ Find the denominator of unit fractions < 1000 that
⍝ has the longest recuring decimal cycle.
Z←1+⌈/CYCLE∆LENGTH¨(2=+⌿0=(⍳1000)∘.|⍳1000)/⍳1000



I did not have a clue on the math for this one, but I did look that up, rather than figuring it out myself. The math came down to the biggest prime denominator with D-1 cycle length if D is the denominator. It was rather fast to compute the close version of primes and then to apply a cycle length function to each of the primes to get the cycle length. It's not the fastest solution, because I could actually short circuit the search if I went in reverse, but I figured that it wasn't worth the loss in clarity on this one.

I would have liked to have found a better cycle length function, though.