summaryrefslogtreecommitdiff
path: root/Homework/cs3460/nbonacci/Assignment1.cpp
blob: 20f7769e08bf91641560135b327550181a9dcfc8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <iostream>
#include <string>
#include <vector>

const double RATIO_THRESHOLD = 0.000001;
const unsigned int DISPLAY_ITERATIONS = 20;

/*
    @param series: unsigned int, the n-bonacci series "degree" (2 -> fib, 3 -> trib)
    @param n: unsigned int, the term to find
    @return long: the nth term of the series-degree n-bonacci series
*/
long nbonacci(unsigned int series, unsigned int n)
{
    if (n <= series)
        return 1;
    
    long sum = 0;
    for (unsigned int i = 1; i <= series; ++i)
        sum += nbonacci(series, n - i);
  
    return sum;
}

/*
    @param title: std::string, the name of the series
    @param series: unsigned int, the degree of the n-bonacci series
    @return void: print the ratio of the series to stdout
*/
void computeNbonacciRatio(std::string title, unsigned int series)
{
    unsigned int i = series+1;
    long prev = 1;
    long curr = nbonacci(series, i); // The first series numbers are one's
    double currRatio = static_cast<double>(curr) / static_cast<double>(prev);
    double prevRatio;
    do 
    {
        prevRatio = currRatio;
        prev = curr;
        curr = nbonacci(series, ++i);
        currRatio = static_cast<double>(curr) / static_cast<double>(prev);
    } while (std::abs(currRatio - prevRatio) > RATIO_THRESHOLD);
  
    // i-1 because the nth number in the sequence corresponds with the (n-1)'th iteration
    std::cout << title << " ratio approches " << currRatio << " after " << i-1 << " iterations." << std::endl; 
}

int main()
{
    std::vector<std::string> names;
    names.push_back("Fibonacci");
    names.push_back("Tribonacci");
    names.push_back("Fourbonacci");
    names.push_back("Fivebonacci");
  
    unsigned int i;
    for (i = 0; i < names.size(); i++) 
    {
        std::cout << "--- " << names.at(i) << " ---" << std::endl;
        for (unsigned int n = 1; n < i+2; n++)
            std::cout << "1 ";
        for (unsigned int n = i+2; n <= DISPLAY_ITERATIONS; n++)
            std::cout << nbonacci(i+2, n) << " ";
        std::cout << std::endl;
    }
  
    std::cout << std::endl;
  
    for (i = 0; i < names.size(); i++) 
      computeNbonacciRatio(names.at(i), i+2);
  
    return 0;
}