HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Different factorial algorithm implementations and measuring their execution time

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
factorialimplementationstimedifferentalgorithmmeasuringandexecutiontheir

Problem

I'm new to C, and as an exercise I'm building 4 different factorial algorithm implementations and measuring their running time. I'm looking for this feedback, especially:

-
The implementation of the factorial algorithms. Can the they be improved? Is there something you would do different? Is something wrong?

-
The implementation of the execution time measuring system. Is there a different/better way to measure function running time? Would you do something differently? Is something wrong?

But I'm also interested in anything else you see wrong in the program.

The program works from the command line:

./factorial  


The program then prints the results to the console.

```
#include
#include
#include

// =========================================================================
// Functions
// =========================================================================

// Using for loop
double iterative_for_factorial(double n) {
double acc = 1;
for (n = n; n > 0; n--) acc *= n;
return acc;
}

// Using while loop
double iterative_while_factorial(double n) {
double acc = 1;
while (n > 0) {
acc *= n;
n--;
}
return acc;
}

// Using recursion
double recursive_factorial(double n) {
if (n \n\n");
return 1;
}

double number = atof(argv[1]);
double times = atof(argv[2]);

double iterative_for_time = timeIt(number, times, iterative_for_factorial) / 1000000.0;
double iterative_while_time = timeIt(number, times, iterative_while_factorial) / 1000000.0;
double recursive_time = timeIt(number, times, recursive_factorial) / 1000000.0;
double recursive_ternary_time = timeIt(number, times, recursive_ternary_factorial) / 1000000.0;

double iterative_for_average = iterative_for_time / times;
double iterative_while_average = iterative_while_time / times;
double recursive_average = recursive_time / times;
do

Solution

I find it odd that the input to the factorial functions is a double rather than an int. There's no need to consider non-integral values of n, nor is there a need to allow large n. In fact, n! will start losing precision at around n = 19, since an IEEE double can only store numbers up to about 9 × 1016 accurately. At n = 171, the result overflows completely.

Context

StackExchange Code Review Q#46361, answer score: 5

Revisions (0)

No revisions yet.