Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Optimize spfrhwotimize

Name: Anonymous 2012-06-18 15:50

Post small pieces of code and optimize each others anus

int is_prime(int num){
    if(num < 1)
        return 0;
    if(num < 3)
        return 1;
    if((num % 2) == 0)
        return 0;
    int i = 3;
    while(num <= i * i){
        if((num % i) == 0)
            return 0;
        i += 2;
    }
    return 1;
}


Time test:

int main(){
    for(int i = 0; i < 10000000; ++i)
        is_prime(i);
    return 0;
}


[code]gcc -O3 prime.c -std=c99
time ./a.out
real    0m0.046s
user    0m0.040s
sys     0m0.000s
[code]

Name: Anonymous 2012-06-18 16:11

int is_prime(int num){
  return PRIME[num];
}


where PRIME[] is a bit array representing all prime numbers less than 10000000

If you're going to be checking that many numbers there's no reason to do the same math over and over again.

Name: Anonymous 2012-06-18 16:19

Name: Anonymous 2012-06-18 16:20

int is_prime(int num)
{
    for (int i = 0; i < num; i++)
    {
        for (int x = 0; x < num; x++)
        {
            for (int a = 0; a < num; a++)
            {
                if(num < 1)
                    return 0;
                if(num < 3)
                    return 1;
                if((num % 2) == 0)
                    return 0;
                int i = 3;
                while(num <= i * i){
                    if((num % i) == 0)
                        return 0;
                    i += 2;
                }
                return 1;
            }
        }
    }
}

int main(){
    for(int i = 0; i < 10000000; ++i)
        is_prime(i);
    return 0;
}


optimized

Name: Anonymous 2012-06-18 16:26

>>2

First you have to initialize that array.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List