diff --git a/examples/fibonacci/README.md b/examples/fibonacci/README.md new file mode 100644 index 0000000000..8b6a3e0e32 --- /dev/null +++ b/examples/fibonacci/README.md @@ -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` \ No newline at end of file diff --git a/examples/fibonacci/inputs/fibonacci.in b/examples/fibonacci/inputs/fibonacci.in new file mode 100644 index 0000000000..fb138b70e5 --- /dev/null +++ b/examples/fibonacci/inputs/fibonacci.in @@ -0,0 +1,3 @@ +// The program input for fibonacci/src/main.leo +[main] +public n: u128 = 63u128; diff --git a/examples/fibonacci/program.json b/examples/fibonacci/program.json new file mode 100644 index 0000000000..c13efaf5c6 --- /dev/null +++ b/examples/fibonacci/program.json @@ -0,0 +1,10 @@ +{ + "program": "fibonacci.aleo", + "version": "0.0.0", + "description": "", + "development": { + "private_key": "APrivateKey1zkpFebmqLzRHMbtdwensSVNUPDWV6WnYw5JcNsYVLDuu8ig", + "address": "aleo1l0l25evjzxac3j4r5xf7uwv3jfnqwll2g9h8j0g5vvk0grnnmq8qexra3d" + }, + "license": "MIT" +} diff --git a/examples/fibonacci/src/main.leo b/examples/fibonacci/src/main.leo new file mode 100644 index 0000000000..b21c735798 --- /dev/null +++ b/examples/fibonacci/src/main.leo @@ -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; + } +}