Revision: 58401
at July 13, 2012 01:21 by gil0mendes

Initial Code
```/*
* Add 1 to a natural x - Test with and without recursion.
* Author: Gil Mendes (gil0mendes)
*
* Created on 11 de Julho de 2012, 18:34
*/

#include <cstdlib>
#include <iostream>

#include <time.h>

using namespace std;

/**
* Add 1 to a natural x.
*
* Function without recursion, very optimized.
* By Gil Mendes (gil0mendes)
*
* @param int64_t number - Natural number (x)
* @return int64_t - Result
*/
int64_t add1ToX(register int64_t number) {
register int64_t total = 0;

do {
total += number--;
} while (number != 0);

return total;
}

/**
* Add 1 to natural x (with recursion)
*
* By Luciana Sondermann
*
* @param int n - Natural number (x)
* @return int - Result
*/
int SomatRec(int n) {
int soma;
if (n == 1) {
soma = 1;
} else {
soma = n + SomatRec(n - 1);
}
return soma;
}

void printResults(int64_t number, int64_t result, clock_t start, clock_t end) {
cout << "The sum of 1 to " << number << " is: " << result << endl;
cout << "Elapsed time (in microseconds): " << (end - start) << endl;

return;
}

/*
* Entry point of the program, tests the time between with and without recursion.
*/
int main(int argc, char** argv) {
int64_t number = 0, result = 0;
clock_t start, end;

while (number <= 0) {
cout << "Enter a natural number: ";
cin >> number;
}

cout << endl << "Without recursion" << endl;
start = clock();
result = add1ToX(number);
end = clock();
printResults(number, result, start, end);

cout << endl << "With recursion" << endl;
start = clock();
result = SomatRec(number);
end = clock();
printResults(number, result, start, end);

return 0;
}```

Initial URL

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

Initial Title
`Add 1 to a natural x.`

Initial Tags

Initial Language
`C++`