I asked the problem of the tribonacci sequence in C ++ & the number of function calls when writing with the recurrence function (python is also available)

Introduction

This is my first article. I found an article that looked interesting, so I tried it. I tried to solve the tribonacci sequence problem with Ruby (time limit 10 minutes) Pioneer -I tried to solve the tribonacci sequence problem with Elixir (time limit 10 minutes) -I tried to solve the tribonacci sequence problem in Ruby, with recursion.

What i did

・ 10 minutes challenge in C ++ (failed because the calculation time is too long) ・ 30 minutes challenge (clear) in C ++ -About the number of function calls when writing recursively (python implementation included)

10 minutes challenge in C ++ (failure)

First of all, I came up with a method to do it recursively and wrote it as it is. The point is to find the 50th of the tribonacci sequence in the first term [1,3,7].

tribonacci_recursive.cpp


#include <iostream>
#include <chrono>
using namespace std;

long long tri_r(int num){
    if(num<=3){
        int templist[3] = {1,3,7};
        return templist[num-1];
    }
    else{
        return tri_r(num-1)+tri_r(num-2)+tri_r(num-3);
    }
}

int main(){
    chrono::system_clock::time_point  start, end;
    start = std::chrono::system_clock::now();
    cout << tri_r(51) << endl;
    end = std::chrono::system_clock::now();
    double e_time = std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count();
    cout << e_time << " ms" << endl;
}

Yes, this doesn't finish the calculation in Matomo time. That's why I rewrote it so that I don't have to do unnecessary calculations. At this point, 10 minutes had passed, so the challenge failed.

30 minutes challenge (clear) in C ++

tribonacci.cpp


long long tri(int num){
    if(num<3){
        int templist[3] = {1,3,7};
        return templist[num-1];
    }
    else{
        long long tri_list[num] = {1,3,7};
        for(int i=3; i<num; i++){
            tri_list[i] = tri_list[i-1] + tri_list[i-2] + tri_list[i-3];
        }
        return tri_list[num-1];
    }
}
int main(){
    chrono::system_clock::time_point  start, end;
    start = std::chrono::system_clock::now();
    for(int i=1; i<51; i++){
        cout << i << "  " << tri(i) << endl;
    }
    end = std::chrono::system_clock::now();
    double e_time = std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count();
    cout << e_time << " ms" << endl;
}

The processing when it is 3 or less is not good, but it can be calculated in an instant. The code outputs from tri (1) to tri (50), but it is still 20 ms. It will be enough.

Number of function calls when written recursively

By the way, when I wrote it in recursion, I understand that it is doing useless calculations, but how does the number of calls to this function increase?

a formula tri_r number of calls
tri_r(1) 1 1
tri_r(2) 1 1
tri_r(3) 1 1
tri_r(4) tri_r(1) + tri_r(2) + tri_r(3) = 1+1+1 3
tri_r(5) tri_r(2) + tri_r(3) + tri_r(4) =1+1+3 5
tri_r(6) tri_r(3) + tri_r(4) + tri_r(5) = 1+3+5 9

You can see it. The number of calls is calculated by the tribonacci sequence of the first term {1,1,1}. It's natural when you think about it, but it's a nice fact.

I tried to measure the calculation time by recursion. Pick up only where it ends with a matomo calculation time (measured 10 times and averaged).

num time(ms)
34 825.2
35 1524.2
36 2856.1

In items 34 to 36, the calculation time is about 1.85 times and 1.87 times, respectively. How about the number of calls? I wrote it in Python, which I'm used to.

tri_calc.py


def tri(num):
    ans_list = [1,1,1]
    if num > 3:
        for i in range(3, num):
            ans_list.append(ans_list[i-3] + ans_list[i-2] + ans_list[i-1])
    return ans_list

calc_num = tri(50)
print(calc_num[35]/calc_num[34])  #1.8392867552142929
print(calc_num[36]/calc_num[35])  #1.8392867552141035

So, you can see that the number of function calls is about 1.84 times each time one term is added. The increase in calculation time is mostly like call overhead.

in conclusion

It was my first post, and it was in Markdown or Nanisore state. Please let me know if you find it easier to read if you write it like this. I'm still a beginner in programming and coding, but it's fun to solve these problems and verify them in various ways. Thank you for reading.

Recommended Posts

I asked the problem of the tribonacci sequence in C ++ & the number of function calls when writing with the recurrence function (python is also available)
[Homology] Count the number of holes in data with Python
I also tried to imitate the function monad and State monad with a generator in Python
How to deal with the problem that build fails when CI / CD of Python Function with AWS Amplify
I want to solve the problem of memory leak when outputting a large number of images with Matplotlib
[Python] Calculate the number of digits required when filling in 0s [Note]
Find the general terms of the Tribonacci sequence with linear algebra and Python
[Python] Precautions when finding the maximum and minimum values in a numpy array with a small number of elements
[Python] I want to know the variables in the function when an error occurs!
Behavior when SIGEV_THREAD is set in sigev_notify of sigevent with timer_create (C language)
I installed Pygame with Python 3.5.1 in the environment of pyenv on OS X
Make the library created by Eigen in C ++ available from Python with Boost.Numpy.
What I did when I got stuck in the time limit with lambda python
Set an upper limit on the number of recursive function iterations in Python
I want to get the file name, line number, and function name in Python 3.4
Dijkstra's algorithm: I asked the problem of AOJ in Python based on the content of Kencho-san's article in the October issue of Software Design.
Output the number of CPU cores in Python
Get the caller of a function in Python
Calculate the total number of combinations with python
The 18th offline real-time writing problem in Python
I implemented the inverse gamma function in python
The 19th offline real-time writing problem in Python
[Python Data Frame] When the value is empty, fill it with the value of another column.
It became TLE when I confirmed the operation with the print function in the competition pro
How to identify the element with the smallest number of characters in a Python list?
Here is one of the apps with "artificial intelligence" that I was interested in.
[New Corona] Is the next peak in December? I tried trend analysis with Python!
How to count the number of occurrences of each element in the list in Python with weight
Check the processing time and the number of calls for each process in python (cProfile)
I thought about why Python self is necessary with the feeling of a Python interpreter
When a local variable with the same name as a global variable is defined in the function
The 15th offline real-time I tried to solve the problem of how to write with python
Two solutions to the problem that it is hard to see the vector field when writing a vector field with quiver () of matplotlib pyplot
Check if the string is a number in python
How to get the number of digits in Python
Get the size (number of elements) of UnionFind in Python
The 14th offline real-time writing reference problem with Python
I tried to solve the problem with Python Vol.1
How to write offline real time I tried to solve the problem of F02 with Python
The value of meta when specifying a function with no return value in Dask dataframe apply
When reading an image with SimpleITK, there is a problem if there is Japanese in the path
Ventilation is important. What I did to keep track of the C02 concentration in the room
I tried to get the number of days of the month holidays (Saturdays, Sundays, and holidays) with python
I wrote a doctest in "I tried to simulate the probability of a bingo game with Python"
How to write when you want to put a number after the group number to be replaced with a regular expression in re.sub of Python
Let's run Fusion 360 with Python Part 11 Since there is no point along the path in the API, I thought of an alternative
I want to output while converting the value of the type (e.g. datetime) that is not supported when outputting json with python