0

this algorithm calculates max prime div using sieve of Eratosthenes. it takes over 7kk kilobytes to calculate x over 1000000000 lol.

some advice how can i optimize it? thanks.

#include <stdio.h>
#include <stdlib.h>

int main()
{
int x, p, i, q, max, min;
scanf ("%d", &x);
int *a = (int*)malloc((abs(x)+1) * sizeof(int));
for (i=0; i<=abs(x); i++)
    a[i] = i;
a[1]=0;
for (p=2; p<=abs(x); p++){
        for (q=p*2; q<=abs(x); q+=p)
            a[q]=0;
} 
max=0;
if (x>=0){
    for(i=0; i<=abs(x); i++)
        if((a[i]!=0) && (abs(x)%a[i]==0))
            if (a[i]>max)
                max=a[i];
printf("%d", max);
free(a);
}
else{
min=abs(x);
for(i=0; i<=abs(x); i++)
        if((a[i]!=0) && (abs(x)%a[i]==0))
            if (a[i]<min)
                min=a[i];
printf ("%d", -min);
free(a);
}
}

1 Answers1

0

You can do implementation optimizations (like using one bit instead of 32) but it will at most get you a 32 optimization factor.

A more interesting thing would be to do algorithm optimisation (like not computing the full sieve but only to sqrt(x))

int x, p, i, q;
scanf_s("%d", &x);
x = abs(x);
int size = sqrt(x); // there is at most one prime number that divide x bigger than sqrt(x)
int *a = (int*)malloc((size + 1) * sizeof(int));
for (i = 0; i <= size; i++)
    a[i] = i;
a[1] = 0;
for (p = 2; p <= size; p++) {
    if (a[p] == 0) { // p is not prime you can skip p
    }
    else {
        while (x % p == 0) { // if p div x, divide it as much as possible
            x /= p;
        }
        if (x == 1) {
            printf("%d", p); 
            break;
        }
        for (q = p * p; q <= size; q += p)
            a[q] = 0;
    }
}
if (x != 1)
    printf("%d", x);
    free(a);
return 0;