mirror of
https://github.com/ProvableHQ/leo.git
synced 2024-12-24 10:41:57 +03:00
Add Fibonacci example
This commit is contained in:
parent
3c2da076ff
commit
e5d053e471
17
examples/fibonacci/README.md
Normal file
17
examples/fibonacci/README.md
Normal file
@ -0,0 +1,17 @@
|
||||
# fibonacci.aleo
|
||||
|
||||
## Build Guide
|
||||
|
||||
To compile this Aleo program, run:
|
||||
```bash
|
||||
aleo build
|
||||
```
|
||||
To run this program, run:
|
||||
```bash
|
||||
leo run fibonacci
|
||||
```
|
||||
|
||||
## Overview
|
||||
This example shows how to calculate Fibonacci number using the fast-doubling method.
|
||||
|
||||
It takes the input data from `inputs/fibonacci.in`
|
3
examples/fibonacci/inputs/fibonacci.in
Normal file
3
examples/fibonacci/inputs/fibonacci.in
Normal file
@ -0,0 +1,3 @@
|
||||
// The program input for fibonacci/src/main.leo
|
||||
[main]
|
||||
public n: u128 = 63u128;
|
10
examples/fibonacci/program.json
Normal file
10
examples/fibonacci/program.json
Normal file
@ -0,0 +1,10 @@
|
||||
{
|
||||
"program": "fibonacci.aleo",
|
||||
"version": "0.0.0",
|
||||
"description": "",
|
||||
"development": {
|
||||
"private_key": "APrivateKey1zkpFebmqLzRHMbtdwensSVNUPDWV6WnYw5JcNsYVLDuu8ig",
|
||||
"address": "aleo1l0l25evjzxac3j4r5xf7uwv3jfnqwll2g9h8j0g5vvk0grnnmq8qexra3d"
|
||||
},
|
||||
"license": "MIT"
|
||||
}
|
46
examples/fibonacci/src/main.leo
Normal file
46
examples/fibonacci/src/main.leo
Normal file
@ -0,0 +1,46 @@
|
||||
program fibonacci.aleo {
|
||||
// This calculates the n-th fibonacci number (up to 64th)
|
||||
transition fibonacci(public n: u128) -> u128 {
|
||||
let f0: u128 = 0u128;
|
||||
let f1: u128 = 1u128;
|
||||
let c: u16 = 0u16;
|
||||
|
||||
let z: u128 = reverse_bits(n);
|
||||
|
||||
for i:u16 in 0u16..8u16 {
|
||||
if n > 0u128 {
|
||||
let f2i1: u128 = f1 * f1 + f0 * f0;
|
||||
let f2i: u128 = f0 * (2u128 * f1 - f0);
|
||||
if z & 1u128.shl(c) == 0u128 {
|
||||
f0 = f2i;
|
||||
f1 = f2i1;
|
||||
} else {
|
||||
f0 = f2i1;
|
||||
f1 = f2i + f2i1;
|
||||
}
|
||||
c = c + 1u16;
|
||||
n = n >> 1u16;
|
||||
}
|
||||
}
|
||||
|
||||
return f0;
|
||||
}
|
||||
|
||||
function reverse_bits(n: u128) -> u128 {
|
||||
let reverse: u128 = 0u128;
|
||||
|
||||
for i:u128 in 0u128..128u128 {
|
||||
if n > 0u128 {
|
||||
reverse = reverse << 1u16;
|
||||
|
||||
if n & 1u128 == 1u128 {
|
||||
reverse ^= 1u128;
|
||||
}
|
||||
|
||||
n = n >> 1u16;
|
||||
}
|
||||
}
|
||||
|
||||
return reverse;
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user