I was trying to solve a project Euler problem ( number 3 ), but I get the error stating " floating point exception (core dumped) ". To tell the truth I don't know the reason for this error (I'm new to C and programming in general), this is the code:
#include <stdio.h>
int fprimos(long long int x){
long long int i;
int f;
while (i < x){
i++;
if (x % i == 0){
f++;
}
}
if (f == 2){
printf("%lli, es primo", x);
}else {
printf("%lli", x);
}
return 0;
}
int main (){
long long int number = 600851475143;
long long int c;
long long int v;
long long int factores[v];
for (c=0; c < number; c++){
if(number % c == 0){
factores[v] = c;
fprimos(factores[v]);
v++;
}
}
}
Note that
v
it doesn't have a value assigned at declare timefactores
, so what size it will ultimately be willfactores
be a complete mystery.In order to create
factores
with a size that allows us to storev
elements, we first have to know what value it is going to havev
. Additionally you should use dynamic memory, since your current design has two problems:factores
you're creating it on the stack. If youv
store a large value, the stack might overflow.Corrected it would be like this:
With this in principle it would be. Of course, you will notice that the performance can be quite poor. The problem with this solution is that dynamic memory allocation is a slow process. If time is an important factor it is important to reduce the number of calls to
malloc
andrealloc
.The following example reduces the number of allocations to 10%