-
Notifications
You must be signed in to change notification settings - Fork 44
/
fibonacci.rs
61 lines (50 loc) · 1.78 KB
/
fibonacci.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
use distaff::{ Program, ProgramInputs, assembly, math::field };
use super::{ Example, utils::parse_args };
pub fn get_example(args: &[String]) -> Example {
// get the length of Fibonacci sequence and proof options from the arguments
let (n, options) = parse_args(args);
// generate the program and expected results
let program = generate_fibonacci_program(n);
let expected_result = vec![compute_fibonacci(n)];
println!("Generated a program to compute {}-th Fibonacci term; expected result: {}",
n,
expected_result[0]);
// initialize stack with 2 values; 1 will be at the top
let inputs = ProgramInputs::from_public(&[1, 0]);
// a single element from the top of the stack will be the output
let num_outputs = 1;
return Example {
program,
inputs,
options,
expected_result,
num_outputs
};
}
/// Generates a program to compute the `n`-th term of Fibonacci sequence
fn generate_fibonacci_program(n: usize) -> Program {
// the program is a simple repetition of 4 stack operations:
// the first operation moves the 2nd stack item to the top,
// the second operation duplicates the top 2 stack items,
// the third operation removes the top item from the stack
// the last operation pops top 2 stack items, adds them, and pushes
// the result back onto the stack
let program = format!("
begin
repeat.{}
swap dup.2 drop add
end
end", n - 1);
return assembly::compile(&program).unwrap();
}
/// Computes the `n`-th term of Fibonacci sequence
fn compute_fibonacci(n: usize) -> u128 {
let mut n1 = 0;
let mut n2 = 1;
for _ in 0..(n - 1) {
let n3 = field::add(n1, n2);
n1 = n2;
n2 = n3;
}
return n2;
}