Wednesday, June 12, 2013

[Project Euler] Problem 7 in C

Problem: Project Euler Problem 7

Implemented Sieve of Eratosthenes in an array.
I refrained from using % (Modulus). I am unsure of how modulus works in C but I believed that it will hinder the performance when working with large numbers. Instead, I have used a for loop with changing steps.

One way of optimizing this would be to somehow delete the non-prime numbers from the array and don't even check the array.
However, since the state of a number is represented in respect to position number of the array, I can not think of a faster way to use the same array to solve the problem.

I have implemented a dirty linked list code in Problem 3a.
I say it's dirty because it works without declaring temporary pointers and does not fully traverse the list to delete a value.

Anyways, without further ado, here is the code I have used.
Feel free to leave a comment.

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

int sieve[1000000];

int main(){
    memset(sieve, -1, sizeof(int)*1000000);
    sieve[2] = 1;
    int i, j, div;
    for (i = 4; i <= 1000000; i+=2){
        sieve[i] = 0;
    }

    i = 3, j = 3, div = 3;
    while (i <= 1000000){
        if (sieve[i] == -1){

            div = i;
            sieve[i] = 1;

            for (j = div*2; j<=1000000; j+=div)
                sieve[j] = 0;
        }

        i++;
    }

    int counter = 0;
    i = 2;
    while (counter != 10001){

        if (sieve[i++] == 1)
            counter++;
    }

    printf("%d\n", --i);

    return 0;
}


Best Execution Time: 0.055s
Answer:

No comments:

Post a Comment