Recent Posts

Count the Number of steps executed/Time taken by each function on various inputs and write complexity of each function


  1. #include <stdio.h>
  2. long calculate(int no);
  3. long calculate_equation(int no);
  4. long calculate_recursion(int no);
  5. int pt=0;
  6. long sum_recursion=0;
  7. int main()
  8. {
  9.       int p,ch;
  10.       long y=0;
  11.       up:
  12.       printf("\nEnter Value for N:");
  13.       scanf("%d",&p);
  14.       while(1)
  15.       {
  16.              printf("\n1. Sum calculate using loop\n2. Sum calculate using equation\n3. Sum calculate using recursion\n4.Close");
  17. printf("\nPlease enter your choice=");
  18. scanf("%d",&ch);
  19. if(ch==1)
  20. {
  21. y=calculate(p);
  22. goto up;
  23. }
  24. else if(ch==2)
  25. {
  26. y=calculate_equation(p);
  27. goto up;
  28. }
  29. else if(ch==3)
  30. {
  31. y=calcculate_recursion(p);
  32. printf("Number of steps=%d",pt);
  33. goto up;
  34. }
  35. else if(ch==4)
  36. {
  37. break;
  38. }
  39. }
  40. }
  41.  
  42. long calculate(int no)
  43. {
  44. int count=1;
  45. int i;
  46. long sum=0;
  47. for(i=1;i<=no;i++)
  48. {
  49. count++;
  50. sum=sum+i;
  51. count++;
  52. }
  53. count++;
  54. count++;
  55. printf("\nNumber of steps= %d",count);
  56. return sum;
  57. }
  58.  
  59. long calculate_equation(int no)
  60. {
  61. long sum=0;
  62. int count=1;
  63. sum=(no*(no+1))/2;
  64. count++;
  65. count++;
  66. printf("\nNumber of steps= %d",count);
  67. count++;
  68. return sum;
  69. }
  70.  
  71. long calculate_recursion(int no)
  72. {
  73. if(no==1)
  74. {
  75. pt++;
  76. pt++;
  77. return 1;
  78. }
  79. else
  80. {
  81. pt++;
  82. pt++;
  83.             return sum_recursion=sum_recursion+calculate_recursion(no-1);
  84. }
  85. }

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:

Powered by Blogger.