Question

In: Computer Science

The n th Triangle Problem Write a code for finding the n th triangle number of...

The n th Triangle Problem Write a code for finding the n th triangle number of triangle sequences: 1, 3, 6, 10, ..., n. That is, your code should accept an integer number, which indicates the triangle levels, and returns how many dots we need to form a triangle with respect to the given level. For example, consider the Fig 1. For n = 3 (can be also written as T3), your code should returns 6.

Provide a single program consists of the following:

• Write a function called TriangularRecursive for the recursive version that takes number of level as an int argument.

Hints:

1) Identify the base case for the TriangularRecursive function.

2) Let the TriangularRecursive function call itself, with proper arguments.

• Write a function called TriangularIterative for the non-recursive (iterative) version that takes number of level as an int argument.

• Write a main function that calls the two functions inside. You should have at least a couple of test cases included in the main function that shows the output for both functions.

After implementing the recursive and non-recursive functions, you are supposed to perform two additional tasks. The first task is to analyze both approaches as follows:

• Establish the recurrence relations for the recursive approach.

• Solve the recurrence and provide the order growth.

• Establish the sum expression for the non-recursive approach.

• Solve the sum and provide the order growth.

The second task is to plot the running time of both approaches for different input sizes (n). To do that, consider ten input size (n) values: 10, 50, 100, 200, 400, 800, 2000, 4000, 8000, 10000. For better precision, run each value ten times and take the average of all ten runs for each case.

Solutions

Expert Solution

#include <bits/stdc++.h>

using namespace std;

int TriangularRecursive(int n)

{

    if (n > 1)

        return n + TriangularRecursive(n - 1);

    else

        return 1;

}

int TriangularIterative(int n)

{

    int i, sum = 0;

    for (i = 1; i <= n; i++)

        sum = sum + i;

    return sum;

}

void checkCase(void)

{

    int vals[] = {10, 50, 100, 200, 400, 800, 2000, 4000, 8000, 10000};

    int i, j;

    time_t start, end;

    double cpu_time_used;

    for (i = 0; i < 10; i++)

    {

        cpu_time_used = 0.0;

        for (j = 0; j < 10; j++)

        {

            start = clock();

            ios_base::sync_with_stdio(false);

            TriangularIterative(vals[i]);

            end = clock();

            cpu_time_used = (double(end - start)) / double(CLOCKS_PER_SEC) + cpu_time_used;

        }

        cout << "\nCPU time taken with " << vals[i] << " levels using Recursion : " << fixed << cpu_time_used / 10.0 << setprecision(9) << " sec";

    }

    for (i = 0; i < 10; i++)

    {

        cpu_time_used = 0.0;

        for (j = 0; j < 10; j++)

        {

            start = clock();

            ios_base::sync_with_stdio(false);

            TriangularIterative(vals[i]);

            end = clock();

            cpu_time_used = (double(end - start)) / double(CLOCKS_PER_SEC) + cpu_time_used;

        }

        cout << "\nCPU time taken with " << vals[i] << " levels using Iteration : " << fixed << cpu_time_used / 10.0 << setprecision(9) << " sec";

    }

}

int main()

{

    int n ,m , recr, iter;

    cout<<"Enter value of n: ";

    cin>>n;

    cout<<"Enter value of n: ";

    cin>>m;

    recr = TriangularRecursive(m);

    iter = TriangularIterative(m);

    cout << "\nnth triangular number With " << m << " levels using Recursion : " << recr;

    cout << "\nnth triangular number With " << m << " levels using Iteration : " << iter;

    recr = TriangularRecursive(n);

    iter = TriangularIterative(n);

    cout << "\nnth triangular number With " << n << " levels using Recursion : " << recr;

    cout << "\nnth triangular number With " << n << " levels using Iteration : " << iter;

    checkCase();

    return 0;

}

//SAMPLE OUTPUT


Related Solutions

In Java: The n^th Harmonic number is the sum of the reciprocals of the first n...
In Java: The n^th Harmonic number is the sum of the reciprocals of the first n natural numbers: H(n) = 1+ 1/2 + 1/3 +1/4 +... +1/n Write a recursive method and an accompanying main method to compute the n^th Harmonic number. I have tried but get a blank and would really apreciate a fully explained code.
This is a Combinatorics Problem Consider the problem of finding the number of ways to distribute...
This is a Combinatorics Problem Consider the problem of finding the number of ways to distribute 7 identical pieces of candy to 3 children so that no child gets more than 4 pieces. Except Stanley (one of the 3 children) has had too much candy already, so he’s only allowed up to 2 pieces. Write a generating function & use your generating function to solve this problem.
Write a java code that: 1) Takes as an argument an integer number, say N 2)...
Write a java code that: 1) Takes as an argument an integer number, say N 2) Creates an array of size N 3) Populates the array with random numbers between 0 and 10 * N. This is, the values of the elements of the array should be random numbers between 0 and 10 * N. 4) Finally, the code outputs the index of the smallest element and the index of the largest element in the array
About finding the number of permutations Let there be n pairs of 2*n students : (1,...
About finding the number of permutations Let there be n pairs of 2*n students : (1, 2) , (3, 4), (5, 6) ... (2n-1 , 2n). We want to find the number of arrangements of students which the pair are not adjacent. In other words, for (2*i) th student, the (2*i -1) th student should not be in his front or back. For example, think of case of n=2. In this case, (1, 4, 3, 2) is not appropriate for...
the language is matlab 1) Write a code that will print a list consisting of “triangle,”...
the language is matlab 1) Write a code that will print a list consisting of “triangle,” “circle,” and “square.” It prompts the user to choose one, and then prompts the user for the appropriate quantities (e.g., the radius of the circle) and then prints its area. If the user enters an invalid choice, the script simply prints an error message. For calculating the area, create separate functions for each choice. Name them as calcTriangle, calcCircle, calcSquare respectively, which are only...
Problem 3 Write code in R or Rstudio (Programming) A prime number is an integer greater...
Problem 3 Write code in R or Rstudio (Programming) A prime number is an integer greater than one whose only factors are one and itself. For example, the first ten prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23 and 29. A twin prime is a prime that has a prime gap of two. Sometimes the term twin prime is used for a pair of twin primes. For example, the five twin prime pairs are (3, 5),...
Write a python code which prints triangle of stars using a loop ( for loop )...
Write a python code which prints triangle of stars using a loop ( for loop ) Remember what 5 * "*" does The number of lines of output should be determined by the user. For example, if the user enters 3, your output should be: * ** *** If the user enters 6, the output should be: * ** *** **** ***** ****** You do NOT need to check for valid input in this program. You may assume the user...
Write C code that contains a function called triangle_generator that outputs a triangle wave at a...
Write C code that contains a function called triangle_generator that outputs a triangle wave at a specified frequency (in hertz) using a specified sample rate (in hertz), and for a specified time duration (in seconds). These parameters are float type. The output you generate are floating point numbers between -1 and 1, one number per output line. The math trig functions in C use radians while all the specifications here are in hertz (cycles per second). One hertz is 2*Pi...
Write a program to implement problem statement below: provide the menu for input N and number...
Write a program to implement problem statement below: provide the menu for input N and number of experiment M to calculate average time on M runs. randomly generated list. State your estimate on the BigO number of your algorithm/program logic. (we discussed in the class) Measure the performance of your program by given different N with randomly generated list with multiple experiment of Ns against time to draw the BigO graph (using excel) we discussed during the lecture. Lab-08-BigBiggerBiggtest.png ***...
Java language please Problem There are N houses for sale. The i-th house costs Ai dollars...
Java language please Problem There are N houses for sale. The i-th house costs Ai dollars to buy. You have a budget of B dollars to spend. What is the maximum number of houses you can buy? Input The first line of the input gives the number of test cases, T. T test cases follow. Each test case begins with a single line containing the two integers N and B. The second line contains N integers. The i-th integer is...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT