M
M
Max2020-02-26 23:05:34
JavaScript
Max, 2020-02-26 23:05:34

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

1 answer(s)
J
jcmvbkbc, 2020-02-27
@max10110

f(n) = n if n < 3, f(n) = f(n−1) +f(n−2) +f(n−3) if n ≥ 3

Well, starting from the fourth value is equal to the sum of the previous three. What is the difficulty?
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 question

Ask a Question

731 491 924 answers to any question