Help making this code run faster for spoj.

Posted by Josh Meredith on Stack Overflow See other posts from Stack Overflow or by Josh Meredith
Published on 2010-05-29T05:35:39Z Indexed on 2010/05/29 5:42 UTC
Read the original article Hit count: 321

Filed under:
|
|
|

I've been doing a few of the challenges on the Sphere Online Judge, but I can't seem to get the second problem (the prime generator) to run within the time limit. Does anyone have any tips for increasing the speed of the following code?

#include <stdio.h>
#include <math.h>

int is_prime(int n);
void make_sieve();
void fast_prime(int n);

int primes[16000];

int main()
{
    int nlines;
    int m, n;
    make_sieve();
    scanf("%d", &nlines);
    for (; nlines >= 1; nlines--) {
        scanf("%d %d", &m, &n);
        if (!(m % 2)) {
            m++;
        }
        for ( ; m < n; m+=2) {
            fast_prime(m);
        }
        printf("\n");
    }
    return 0;
}

/* Prints a number if it's prime. */
inline void fast_prime(int n)
{
    int j;
    for (int i = 0; ((j = primes[i]) > -1); i++) {
        if (!(n % j)) {
            return;
        }
    }
    printf("%d\n", n);
}

/* Create an array listing prime numbers. */
void make_sieve()
{
    int j = 0;
    for (int i = 0; i < 16000; i++) {
        primes[i] = -1;
    }
    for (int i = 2; i < 32000; i++) {   
        if (i % 2) {
            if (is_prime(i)) {
                primes[j] = i;
                j++;
            }
        }
    }
    return;
}

/* Test if a number is prime. Return 1 if prime. Return 0 if not. */
int is_prime(int n)
{
    int rootofn;
    rootofn = sqrt(n);    
    if ((n <= 2) || (n == 3) || (n == 5) || (n == 7)) {
        return 1;
    }
    if (((n % 2) == 0) || ((n % 3) == 0) || ((n % 5) == 0) || ((n % 7) == 0)) {
        return 0;
    }
    for (int i = 11; i < rootofn; i += 2) {
        if ((n % i) == 0) {
            return 0;
        }
    }
    return 1;
}

© Stack Overflow or respective owner

Related posts about c

    Related posts about speed