I’m not entirely sure, but isn’t there a way to make a function so it only really runs once and then the rest if the times it just returns the computed value from the first run? Is there a way to do that? I apologize I have no examples for y’all
double foo()
{
staticbool isFirst { true };
staticdouble v {};
if ( isFirst )
{ // calculate at length, fashion the result in v
isFirst = false;
}
return v;
}
It's the simple concept of using a bool.
If this is just a stand alone function, the static bool 'belongs' to the function, but there's only 1. All calls after the first will return the cached v (unless isFirst is reset to true).
#include <iostream>
using ull = unsignedlonglong;
// Memoized recursive fibonacci.
// Can only go up to fib(93) in 64-bits.
ull fib(int n)
{
static ull f[94];
// out-of-range (handle however you want)
if (n < 0 || n > 93) return 0;
// 0 and 1 are base cases.
if (n < 2) return n;
// If f[n] isn't 0 it's already been calculated, so return that.
// Otherwise recursively calculate fib(n), storing the result in f[n]
// and returning it.
return f[n] ? f[n] : f[n] = fib(n - 1) + fib(n - 2);
}
int main() {
for (;;) {
std::cout << "fib: ";
int n;
std::cin >> n;
std::cout << fib(n) << '\n';
}
}
Without the memoization it wouldn't be able to calculate fib(93) within, I don't know how long. A long time. The complexity of a naive recursive fib is O(1.6^n). 1.6 is a rounded off "golden ratio", so you could be more accurate. 1.6 ^ 93 is 9.6 billion billion.
Sry I keep on getting distracted 😭 thanks that was it. So then when I make a static variable in a function it is the same car every time? Kinda? I don’t really understand that well
I'm not sure where "cars" come into it (presumably your program is about that), but a static variable inside a function is exactly like a global variable outside the function except that it's restricted to the scope of the function. So it is one variable, initialized to zeroed memory at program startup, and retaining any changes you make to it across function calls.