CS29003 Algorithms Laboratory Assignment 1: Logarithmic Vs Linear Vs Exponential Growth of Functions
CS29003 Algorithms Laboratory Assignment 1: Logarithmic Vs Linear Vs Exponential Growth of Functions
1. Do not use any global variable unless you are explicitly instructed so.
4. Name your file as <roll_no>_<assignment_no>. For example, if your roll number is 14CS10001
and you are submitting assignment 3, then name your file as 14CS10001_3.c or 14CS10001_3.cpp
as applicable.
5. Write your name, roll number, and assignment number at the beginning of your program.
Consider the situation of a spread of a viral disease. In the 0-th month, there was no infected person.
The disease begins with one infected person in the first month. Once a person gets infected, he/she
remains infected for two months. Every infected person infects two healthy person in the first month
and one healthy person in the second month. Let In denote the number of infected person in the n-th
month. Then we have the following.
0 if n = 0
In = 1 if n = 1
2In−1 + In−2 if n > 2
In this assignment, we will compute the number In of infected people in the n-th month in various
ways. For this assignment, you can assume that n is at most 40. You do not need to verify this. Simply
take the value of n as input from the user (using keyboard) and output In .
1
compute_recursive(n){
if n=0, then return 0
else if n=1, then return 1
else if n>1, then return 2*compute_recursive(n-1)+compute_recursive(n-2);
}
What is the running time of this algorithm? Implement this algorithm in a function whose prototype
is given below. You need to follow the prototype strictly.
Now you compute In using the above formula. Use the following function prototype.
Now you compute In using the above formula. Your algorithm should run in O(log n) time. Use the
following function prototype.
main()
1. Read n from the user.
2. Compute In by all the four methods by calling appropriate functions. Also output the amount of
time (in seconds) taken by each method.
2
One possible way to compute execution time of some piece of code is the following. You are allowed
to use any other method.
#include <stdio.h>
#include <time.h> // for clock_t, clock(), CLOCKS_PER_SEC
int main()
{
// to store execution time of code
double time_spent = 0.0;
return 0;
}
Submit a single .c or .cpp file. Your code should get compiled properly by gcc or g++ compiler.
Sample Output
Write n: 10
I_10 (computed using iterative method) = 2378.000000
Time taken in iterative method = 0.000076 seconds
————————————————————————————————————–
Write n: 40
I_40 (computed using iterative method) = 723573111879672.000000
Time taken in iterative method = 0.000062 seconds
3
I_40 (computed using recursive method) = 723573111879672.000000
Time taken in recursive method = 0.777038 seconds
————————————————————————————————————–