## With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

No credit card required

# An NDK Example: Fibonacci

Because the NDK is well-suited for computationally intensive applications, I wanted to find an example where we can implement a relatively simple algorithm in both native code and Java to compare their relative speeds.

So I picked a Fibonacci algorithm as the example. It’s a fairly simple algorithm that can be implemented easily in both C and Java. Additionally, we can implement it recursively as well as iteratively.

As a quick refresher, the Fibonacci series is defined as:

```fib(0)=0
fib(1)=1
fib(n)=fib(n-1)+fib(n-2)```

So the Fibonacci sequence looks like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, and so on.

In this example, we are going to:

• Create the Java class representing the Fibonacci library.

• Create the native code header file.

• Implement the native code by writing C code.

• Compile everything and build a shared library.

• Use this native code inside an Android activity.

## FibLib

`FibLib` is where we declare our algorithms for computing the Fibonacci sequence. We have a total of four versions of the Fibonacci algorithm:

• Java recursive version

• Java iterative version

• Native recursive version

• Native iterative version

We’ll write the Java implementation in Example 15-1 and do the native ones in C later.

Example 15-1. FibLib.java

```package com.marakana;

public class FibLib {

// Java implementation - recursive
public static long fibJ(long n) {  //  if (n <= 0) return 0; if (n == ...```

## With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

No credit card required