Count the Number of steps executed/Time taken by each function on various inputs and write complexity of each function
- #include <stdio.h>
- long calculate(int no);
- long calculate_equation(int no);
- long calculate_recursion(int no);
- int pt=0;
- long sum_recursion=0;
- int main()
- {
- int p,ch;
- long y=0;
- up:
- printf("\nEnter Value for N:");
- scanf("%d",&p);
- while(1)
- {
- printf("\n1. Sum calculate using loop\n2. Sum calculate using equation\n3. Sum calculate using recursion\n4.Close");
- printf("\nPlease enter your choice=");
- scanf("%d",&ch);
- if(ch==1)
- {
- y=calculate(p);
- goto up;
- }
- else if(ch==2)
- {
- y=calculate_equation(p);
- goto up;
- }
- else if(ch==3)
- {
- y=calcculate_recursion(p);
- printf("Number of steps=%d",pt);
- goto up;
- }
- else if(ch==4)
- {
- break;
- }
- }
- }
- long calculate(int no)
- {
- int count=1;
- int i;
- long sum=0;
- for(i=1;i<=no;i++)
- {
- count++;
- sum=sum+i;
- count++;
- }
- count++;
- count++;
- printf("\nNumber of steps= %d",count);
- return sum;
- }
- long calculate_equation(int no)
- {
- long sum=0;
- int count=1;
- sum=(no*(no+1))/2;
- count++;
- count++;
- printf("\nNumber of steps= %d",count);
- count++;
- return sum;
- }
- long calculate_recursion(int no)
- {
- if(no==1)
- {
- pt++;
- pt++;
- return 1;
- }
- else
- {
- pt++;
- pt++;
- return sum_recursion=sum_recursion+calculate_recursion(no-1);
- }
- }
Output
1. To calculate the sum of 1
to N number using a loop.
NO
|
INPUT
|
COUNT
|
1
|
10
|
23
|
2
|
100
|
203
|
3
|
1000
|
2003
|
4
|
10000
|
20003
|
5
|
50000
|
200003
|
No comments: