Posted By

gil0mendes on 07/13/12


Tagged


Versions (?)

Add 1 to a natural x.


 / Published in: C++
 

Code used to test the differences between "sum up a natural x 1", with or without recursion.

  1. /*
  2.  * Add 1 to a natural x - Test with and without recursion.
  3.  * Author: Gil Mendes (gil0mendes)
  4.  *
  5.  * Created on 11 de Julho de 2012, 18:34
  6.  */
  7.  
  8. #include <cstdlib>
  9. #include <iostream>
  10.  
  11. #include <time.h>
  12.  
  13. using namespace std;
  14.  
  15. /**
  16.  * Add 1 to a natural x.
  17.  *
  18.  * Function without recursion, very optimized.
  19.  * By Gil Mendes (gil0mendes)
  20.  *
  21.  * @param int64_t number - Natural number (x)
  22.  * @return int64_t - Result
  23.  */
  24. int64_t add1ToX(register int64_t number) {
  25. register int64_t total = 0;
  26.  
  27. do {
  28. total += number--;
  29. } while (number != 0);
  30.  
  31. return total;
  32. }
  33.  
  34. /**
  35.  * Add 1 to natural x (with recursion)
  36.  *
  37.  * By Luciana Sondermann
  38.  *
  39.  * @param int n - Natural number (x)
  40.  * @return int - Result
  41.  */
  42. int SomatRec(int n) {
  43. int soma;
  44. if (n == 1) {
  45. soma = 1;
  46. } else {
  47. soma = n + SomatRec(n - 1);
  48. }
  49. return soma;
  50. }
  51.  
  52. void printResults(int64_t number, int64_t result, clock_t start, clock_t end) {
  53. cout << "The sum of 1 to " << number << " is: " << result << endl;
  54. cout << "Elapsed time (in microseconds): " << (end - start) << endl;
  55.  
  56. return;
  57. }
  58.  
  59. /*
  60.  * Entry point of the program, tests the time between with and without recursion.
  61.  */
  62. int main(int argc, char** argv) {
  63. int64_t number = 0, result = 0;
  64. clock_t start, end;
  65.  
  66. while (number <= 0) {
  67. cout << "Enter a natural number: ";
  68. cin >> number;
  69. }
  70.  
  71. cout << endl << "Without recursion" << endl;
  72. start = clock();
  73. result = add1ToX(number);
  74. end = clock();
  75. printResults(number, result, start, end);
  76.  
  77. cout << endl << "With recursion" << endl;
  78. start = clock();
  79. result = SomatRec(number);
  80. end = clock();
  81. printResults(number, result, start, end);
  82.  
  83. return 0;
  84. }

Report this snippet  

You need to login to post a comment.