A Better Recursive Solution

A better approach is to use recursion where you generate the numbers in their natural order. this makes the code look a little less elegant, but it does result in a massive performance improvement (significantly better than the “classic” solution):

  package examples.fibonnacci;
  
  agent RecFib {
      module System system;
      module Console console;
      module Debug debug;

      rule +!main(list args) {
          long S = system.currentTimeMillis();
          !fib(long X, 1l, 1l, 500l);
          console.println("FIB(50) = " + X);
          console.println("Duration: " +
              (system.currentTimeMillis() - S));
          system.terminate();
      }

      rule +!fib(long R, long A, long B, long N) : N == 3 {
          R = A + B;
      }
  
      rule +!fib(long R, long A, long B, long N) {
          !fib(R, B, A+B, N-1);
      }
  }

This approach combines the best of both worlds – the iterative approach of the “classic” solution combined with an elegant recursive algorithm. The result is a VERY FAST solution (~4 times faster for fib(500)).