Answer the question
In order to leave comments, you need to log in
How to solve a problem in an iterative process?
The function f is defined by the rule: f(n) = n if n < 3 and f(n) = f(n−1) +f(n−2) +f(n−3) if n ≥ 3. Write a procedure that calculates f using an iterative process. I've been sitting here for 2 days and can't decide. With the help of recursion, everything is done quickly and head-on, with iterative it is already more difficult, but the speed increases significantly. Thanks in advance!
Answer the question
In order to leave comments, you need to log in
f(n) = n if n < 3, f(n) = f(n−1) +f(n−2) +f(n−3) if n ≥ 3
int f(int n)
{
int v[3] = {0, 1, 2};
int i;
if (n < 3)
return n;
for (i = 3; i <= n; ++i)
v[i % 3] = v[0] + v[1] + v[2];
return v[n % 3];
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question