# Fibonacci

### Description

**The Fibonacci sequence is a set of integers** (the Fibonacci numbers) that starts with a zero, followed by a one, then by another one, and then by a series of steadily increasing numbers. The sequence follows the rule that each number is equal to the sum of the preceding two numbers.

The Fibonacci sequence begins with the following 14 integers:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233 ...

From the third number onward, each one follows the same rule. For example, the seventh number is 8, which comes after 3 and 5, and 3 + 5 = 8.

The sequence can theoretically continue to infinity, using the same formula for each new number. Some resources show the Fibonacci sequence starting with a one instead of a zero, but this is fairly uncommon.

### Executing Fibonacci <a href="#using-bacalhau-to-execute-duckdb-processing" id="using-bacalhau-to-execute-duckdb-processing"></a>

We use Truebit to execute the Fibonacci task to get a verified result.

### The Code

You can find the Fibonacci example within the folder *truebit-nextgen-examples/function-tasks/\<language>/fibonacci*.&#x20;

{% tabs %}
{% tab title="Rust" %}
📁 src\
└─ 📄 main.rs \
📄 Cargo.toml\
📄 Cargo.lock

{% hint style="info" %}
The target folder and the Cargo.lock file are going to be generated after running the [build](#step-2-build-the-source-code) command within the truebit-cli
{% endhint %}
{% endtab %}

{% tab title="C" %}
📁 src \
└─ 📄 main.c\
📄 compile.sh

{% hint style="info" %}
The xxx folder and the xxxx file are going to be generated after running the [build](#step-2-build-the-source-code) command within the truebit-cli
{% endhint %}
{% endtab %}

{% tab title="C++" %}
📁 src \
└─ 📄 main.cpp\
&#x20;📄 compile.sh

{% hint style="info" %}
The xxx folder and the xxxx file are going to be generated after running the [build](#step-2-build-the-source-code) command within the truebit-cli
{% endhint %}
{% endtab %}

{% tab title="Js" %}
📁 src \
└─ 📄 main.js\
&#x20;📁 dist\
└─ 📄 main.js\
📄 package-lock.json\
📄 package.json

{% hint style="info" %}
The ***dist*** folder and the ***main.js*** file are going to be generated after running the `npx rollup -c` command. More information click [here](https://devs.truebit.io/developing-truebit-tasks/supported-languages#development-flow).
{% endhint %}
{% endtab %}

{% tab title="Python" %}
📁 src \
└─ 📄 task.py
{% endtab %}
{% endtabs %}

#### Source

{% tabs %}
{% tab title="Rust" %}
**main.rs**

<pre class="language-rust" data-overflow="wrap" data-line-numbers><code class="lang-rust"><strong>fn fibonacci(n: u32) -> u64 {
</strong>    if n == 0 {
        return 0;
    } else if n == 1 {
        return 1;
    }

    let mut a = 0;
    let mut b = 1;
    let mut c = 0;

    for _i in 2..=n {
        c = a + b;
        a = b;
        b = c;
    }

    return c;
}

fn run_task(input: String) -> String {
    fibonacci(input.parse().unwrap()).to_string()
}

fn main() {
    let input: String =
        std::fs::read_to_string("input.txt").expect("Could not read from input.txt");
    let output: String = run_task(input);
    std::fs::write("output.txt", output).expect("Could not write to output.txt");
}
</code></pre>

{% endtab %}

{% tab title="C" %}
**main.c**

{% code overflow="wrap" lineNumbers="true" %}

```c
#include <stdio.h>
#include <stdlib.h>

unsigned long long fibonacci(int n) {
    if (n == 0) {
        return 0;
    } else if (n == 1) {
        return 1;
    }

    unsigned long long a = 0;
    unsigned long long b = 1;
    unsigned long long c = 0;

    for (int i = 2; i <= n; i++) {
        c = a + b;
        a = b;
        b = c;
    }

    return c;
}

char* runTask(const char* input) {
    int inputValue = atoi(input);
    unsigned long long result = fibonacci(inputValue);
    
    char* output = (char*)malloc(20); 
    sprintf(output, "%llu", result);
    
    return output;
}

int main() {
    FILE* inputFile = fopen("input.txt", "r");
    if (inputFile == NULL) {
        perror("Error opening input.txt");
        return 1;
    }

    char inputBuffer[256]; 
    if (fgets(inputBuffer, sizeof(inputBuffer), inputFile) == NULL) {
        perror("Error reading input.txt");
        fclose(inputFile);
        return 1;
    }

    fclose(inputFile);

    char* output = runTask(inputBuffer);

    FILE* outputFile = fopen("output.txt", "w");
    if (outputFile == NULL) {
        perror("Error opening output.txt");
        free(output);
        return 1;
    }

    fprintf(outputFile, "%s", output);
    fclose(outputFile);
    free(output);

    printf("output.txt\n");

    return 0;
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
**main.cpp**

{% code overflow="wrap" lineNumbers="true" %}

```cpp
#include <iostream>
#include <fstream>
using namespace std;

unsigned long long fibonacci(int n) {
    if (n == 0) {
        return 0;
    } else if (n == 1) {
        return 1;
    }

    unsigned long long a = 0;
    unsigned long long b = 1;
    unsigned long long c = 0;

    for (int i = 2; i <= n; i++) {
        c = a + b;
        a = b;
        b = c;
    }

    return c;
}

string runTask(const string& input) {
    int inputValue = stoi(input);
    return to_string(fibonacci(inputValue));
}

int main() {
    ifstream inputFile("input.txt");
    if (!inputFile) {
        cerr << "Could not read from input.txt" << endl;
        return 1;
    }

    string input;
    getline(inputFile, input);
    inputFile.close();

    string output = runTask(input);

    ofstream outputFile("output.txt");
    if (!outputFile) {
        cerr << "Could not write to output.txt" << endl;
        return 1;
    }

    outputFile << output << endl;
    outputFile.close();

    cout << "Output written to output.txt" << endl;

    return 0;
}
```

{% endcode %}
{% endtab %}

{% tab title="Js" %}
**fibonacci.js**

{% code overflow="wrap" lineNumbers="true" %}

```javascript
import fs from 'fs';

function fibonacci(n) {
    if (n === 0) {
        return 0;
    } else if (n === 1) {
        return 1;
    }

    let a = 0;
    let b = 1;
    let c = 0;

    for (let i = 2; i <= n; i++) {
        c = a + b;
        a = b;
        b = c;
    }

    return c;
}

function runTask(input) {
    return fibonacci(parseInt(input)).toString();
}

let data = fs.readFileSync('input.txt', 'utf8')
const output = runTask(data);
fs.writeFileSync('output.txt', output)
```

{% endcode %}
{% endtab %}

{% tab title="Python" %}
{% code overflow="wrap" lineNumbers="true" %}

```python
def fibonacci(n):
    """Calculate the nth Fibonacci number iteratively."""
    if n == 0:
        return 0
    elif n == 1:
        return 1

    a, b = 0, 1
    for _ in range(2, n + 1):
        c = a + b
        a = b
        b = c
    return c

def run_task(input_string):
    """Convert input string to integer, compute Fibonacci, and return as string."""
    return str(fibonacci(int(input_string)))

def main():
    """Main function to read, process, and write Fibonacci number to a file."""
    try:
        with open("input.txt", "r") as file:
            input_string = file.read().strip()
    except FileNotFoundError:
        print("Error: The file 'input.txt' does not exist.")
        return
    except Exception as e:
        print(f"An error occurred while reading 'input.txt': {e}")
        return

    try:
        output_string = run_task(input_string)
    except ValueError:
        print("Error: Input must be an integer.")
        return
    except Exception as e:
        print(f"An error occurred while processing the input: {e}")
        return

    try:
        with open("output.txt", "w") as file:
            file.write(output_string)
    except Exception as e:
        print(f"An error occurred while writing to 'output.txt': {e}")

if __name__ == "__main__":
    main()
```

{% endcode %}

{% endtab %}
{% endtabs %}

#### In/Out Parameters

In order to send parameters to the Truebit task, you need to open the "input.txt" file and get the value from there. For now, only one input parameter is allowed.

{% tabs %}
{% tab title="Rust" %}
{% code overflow="wrap" %}

```rust
let input: String = std::fs::read_to_string("input.txt").expect("Could not read from input.txt");
```

{% endcode %}
{% endtab %}

{% tab title="C" %}
{% code overflow="wrap" %}

```c
FILE* inputFile = fopen("input.txt", "r");
if (inputFile == NULL) {
    perror("Error opening input.txt");
    return 1;
}

char inputBuffer[256]; 
if (fgets(inputBuffer, sizeof(inputBuffer), inputFile) == NULL) {
    perror("Could not read from input.txt");
    fclose(inputFile);
    return 1;
}

fclose(inputFile);
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code overflow="wrap" %}

```cpp
ifstream inputFile("input.txt");
if (!inputFile) {
    cerr << "Could not read from input.txt" << endl;
    return 1;
}

string input;
getline(inputFile, input);
inputFile.close();
```

{% endcode %}
{% endtab %}

{% tab title="Js" %}
{% code overflow="wrap" %}

```javascript
let data = fs.readFileSync('input.txt', 'utf8')
```

{% endcode %}
{% endtab %}

{% tab title="Python" %}

```python
with open("input.txt", "r") as file:
input_string = file.read().strip()
```

{% endtab %}
{% endtabs %}

To retrieve the output value from the Truebit task, you need save it in the "output.txt" file.

{% tabs %}
{% tab title="Rust" %}
{% code overflow="wrap" %}

```rust
std::fs::write("output.txt", output).expect("Could not write to output.txt");
```

{% endcode %}
{% endtab %}

{% tab title="C" %}
{% code overflow="wrap" %}

```c
FILE* outputFile = fopen("output.txt", "w");
if (outputFile == NULL) {
    perror("Error opening output.txt");
    free(output);
    return 1;
}

fprintf(outputFile, "%s", output);
fclose(outputFile);
free(output);
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code overflow="wrap" %}

```cpp
ofstream outputFile("output.txt");
if (!outputFile) {
    cerr << "Could not write to output.txt" << endl;
    return 1;
}

outputFile << output << endl;
outputFile.close();

```

{% endcode %}
{% endtab %}

{% tab title="Js" %}
{% code overflow="wrap" %}

```javascript
fs.writeFileSync('output.txt', output)
```

{% endcode %}
{% endtab %}

{% tab title="Python" %}

```python
with open("output.txt", "w") as file:
file.write(output_string)
```

{% endtab %}
{% endtabs %}

### Trying Out

We will use the [Truebit CLI](https://devs.truebit.io/developing-truebit-tasks/truebit-cli-reference) to [compile](https://devs.truebit.io/developing-truebit-tasks/how-to-create-function-tasks/reverse-alphabet#step-2-build-the-source-code) and [test](https://devs.truebit.io/developing-truebit-tasks/how-to-create-function-tasks/reverse-alphabet#step-3-try-the-code) our source code. Once finalized, we will [deploy](#step-4-deploy-the-task) it to the Coordination Hub so that any user with the `namespace` and `taskname` can access or execute it.

#### Step 1: Create The Fibonacci Source Code

Within the src folder you will find a file called main in the case of *Rust, C, C++, JS,* and *task.py* in the case of Python. This is the fibonacci implementation that will be used for testing purpose.

#### Step 2: Build The Source Code

Execute the [build](https://devs.truebit.io/truebit-cli-reference#build) command against Truebit node to get an instrumented Truebit task.

{% hint style="info" %}
This in an example of how to build a JS task.&#x20;
{% endhint %}

{% code overflow="wrap" %}

```bash
truebit build truebit-nextgen-examples/function-tasks/js/fibonacci/dist -l js
```

{% endcode %}

#### Output

{% code overflow="wrap" %}

```bash
Building the function task
Your function task is ready.
Use the following TaskId for execution or deployment: <taskId>
```

{% endcode %}

{% hint style="info" %}
The `taskId` will always starts with the language prefix + "\_" + cID
{% endhint %}

#### Step 3: Try The Code

Execute the [start](https://devs.truebit.io/truebit-cli-reference#start) command against the Truebit node to test our Algorithm. You will need to submit the instrumented task id + the input parameter.

{% code overflow="wrap" %}

```bash
truebit start <taskId> 10
```

{% endcode %}

* \[`taskId`]: Add the taskId generated in the previous step.&#x20;

#### Output

{% code overflow="wrap" %}

```bash
Executing the function Task
Execution Id: e406e754-b90b-4c62-9394-2cf0bb2c5647
Task executed with status: succeed
Task executed with result: 55
Task resource usage:
┌───────────────┬───────────────┬───────────────┬───────┬─────────────┬──────────┐
│ (index)       │ Unit          │ Limits        │ Peak  │ Last status │ Capacity │
├───────────────┼───────────────┼───────────────┼───────┼─────────────┼──────────┤
│ Gas           │ 'Steps'       │ 1099511627776 │ 'N/A' │ 1907033199  │ 577      │
│ Nested calls  │ 'Calls'       │ 65536         │ 6387  │ 6352        │ 10       │
│ Frame memory  │ 'Bytes'       │ 524288        │ 20115 │ 19073       │ 26       │
│ System memory │ '64 Kb pages' │ 2048          │ 87    │ '𝚫 1'       │ 24       │
└───────────────┴───────────────┴───────────────┴───────┴─────────────┴──────────┘
```

{% endcode %}

#### Step 4: Deploy The Task

Last, but not least, execute the [deploy](https://devs.truebit.io/truebit-cli-reference#deploy) command to deploy our task to the coordination hub, so that anyone with the namespace, taskname and the [API key](https://devs.truebit.io/task-authorization#task-authorization-process) can execute it.

<pre class="language-bash" data-overflow="wrap"><code class="lang-bash"><strong>truebit deploy &#x3C;namespace> &#x3C;taskname> --taskId
</strong></code></pre>

* \[`taskId`]: Add the taskId generated in step 2.

**Output**

{% code overflow="wrap" %}

```bash
The function task has been deployed successfully.
The Task <taskName> version <version> was registered successfully in namespace <namespace>
```

{% endcode %}
