rhai/scripts/fibonacci.rhai

33 lines
637 B
JavaScript
Raw Permalink Normal View History

2022-07-24 17:03:35 +02:00
//! This script calculates the n-th Fibonacci number using a really dumb algorithm
//! to test the speed of the scripting engine.
2020-04-13 17:38:10 +02:00
2021-04-16 04:33:55 +02:00
const TARGET = 28;
const REPEAT = 5;
2021-09-27 05:13:48 +02:00
const ANSWER = 317_811;
2020-04-13 17:38:10 +02:00
fn fib(n) {
if n < 2 {
2021-05-24 06:12:16 +02:00
n
2020-04-13 17:38:10 +02:00
} else {
fib(n-1) + fib(n-2)
}
}
2021-09-21 04:41:09 +02:00
print(`Running Fibonacci(${TARGET}) x ${REPEAT} times...`);
2020-04-13 17:38:10 +02:00
print("Ready... Go!");
let result;
2020-05-13 05:56:48 +02:00
let now = timestamp();
2021-12-15 05:06:17 +01:00
for n in 0..REPEAT {
2021-05-24 06:12:16 +02:00
result = fib(TARGET);
}
2020-04-13 17:38:10 +02:00
2021-04-04 17:22:45 +02:00
print(`Finished. Run time = ${now.elapsed} seconds.`);
2020-05-13 05:56:48 +02:00
2021-04-16 04:33:55 +02:00
print(`Fibonacci number #${TARGET} = ${result}`);
2020-04-13 17:38:10 +02:00
2021-09-27 05:13:48 +02:00
if result != ANSWER {
print(`The answer is WRONG! Should be ${ANSWER}!`);
}