I've been trying to compare functions speed in C and there is something I cannot understand,
I tried to get sum of prime numbers(1 to 100000)
in recursive I get 2.1.... sec
int sumOfPrime(unsigned int top)
{
if( top % 2 == 0 ) top -= 1;
static int total = 2; // sum of prime numbers
int i;
int control=0; // prime or not
if( top == 2 | top < 2) return total;
for (i = 3; i < (top/2)+1; i++)
{
if( top % i == 0 ) // if there is a multiple
{
control++;
break;
}
}
if( control == 0 ){
total += top;
}
return sumOfPrime(top-2);
}
in iterative which is O(n^2) I get 1.14 sec
int sumOfPrime(unsigned int top)
{
unsigned int total = 2;
int count;
int i,j;
for (i = 3; i < top; i+=2)
{
count = 0;
for (j = 3; j < (i/2)+1; j+=2)
{
if( i % j == 0 )
{
count++;
break;
}
}
if( count == 0 ){
total += i;
}
}
return total;
}
and then I tried it in tail recursive and still I got 2.1 almost exactly same time,
int sumOfPrime(unsigned int top,unsigned int total)
{
if( top % 2 == 0 ) top -= 1;
//static int total = 2;
int i; // for for loop
int control=0; // prime or not
if( top == 2 | top < 2) return total+2;
for (i = 3; i < (top/2)+1; i++)
{
if( top % i == 0 ) // if there is a multiple
{
control++; // add +1 to control
break;
}
}
if( control == 0 ){ // if its primme
total += top;
}
return sumOfPrime(top-2,total);
}
Here is the thing we use recursive for speed in some situations like merge-sort so what is the situations like that ?
Is there a some spesific rules about when to use it for speed ? or What am I missing ? I'm really more comfortable recursive than iterative and I really want to use it but this speed diffrences gives me stomachache.