1

Recently, I have tried to work using APL but have had difficulty conceptualizing it. For instance, let's say I want to make a program g<-pollard x, where the function computes if a number x is prime or factorable through the Pollard-Rho method.

I know the method itself, but I don't know where to start actually integrating it into APL. Should I start by creating an entirely new function f(x) for use in this function, or should I include everything in the code? How would I go about saving the x from the previous run to use for the next run? Note that I'm not asking for an entire program, just some recommendations to get me started.

user17103
  • 51
  • 3

1 Answers1

4

First off, this is a bit more than trivial for trying out a language you do not know. Be that as it may, I found the problem intriguing and have whipped up a couple of solutions for you. These are done using Dyalog APL. For an APL novice they will require some study.

The first solution is a simple function for Pollard Rho (as defined by Wikipedia), with the f(x) embedded directly in the main function:

PollardRho←{
     n←⍵
     ⍺←2 2 1
     x y d←⍺
     f←{n|1+⍵*2}
     x←f x
     y←f f y
     d←n∨|x-y
     d=n:'Failure'
     d≠1:d
     x y d ∇ n
 }

We can try this out in the APL session:

     PollardRho 8051
97

The second method extracts the function f(x) from the main function, and provides it as an argument, which is convenient for using different functions for f(x). In APL, a function that takes a function as an argument is called an operator:

PollardRho2←{
     n←⍵
     ⍺←2 2 1
     x y d←⍺
     x←n ⍺⍺ x
     y←n ⍺⍺ n ⍺⍺ y
     d←n∨|x-y
     d=n:'Failure'
     d≠1:d
     x y d ⍺⍺ ∇∇ n
 }

We can run this in the session by first defining the function f(x) and providing it as the left operand:

      f←{⍺|1+⍵*2}
      f PollardRho2 8051
97

Note that both solutions use tail recursion.

I hope you find this useful.

Paul Mansour
  • 1,436
  • 9
  • 11
  • Why did you write `⍺⍺ ∇∇`? The operand never changes, so you might as well just write `∇`. – marinus Oct 01 '14 at 15:09
  • But the function f(x) can change, which is why it was extracted from the first example function PollardRho and provided as an operand to the operator PollardRho2. See the wikipedia entry on Pollard-Rho, which states that the function f(x) is in fact an input into the algorithm. – Paul Mansour Oct 02 '14 at 15:33