Wednesday, October 9, 2013

50 Problems solved (the latest in C)

After a little under 2 months working through this Project Euler Language Challenge, I have solved my 50th problem. This last problem itself was not particularly hard, as I freed up C in order to make it be not so hard, but this landmark means a couple of things:

  • Problems will start getting harder, so I may be solving problems with less frequency
  • I will need to expand to a class of languages I have tried to avoid as much as possible: really old languages like ALGOL and COBOL (and anything that is spelled in all-caps).
  • I have reached 'Level 2' on Project Euler (which just means I get a fancy little check mark on my profile page, and the satisfaction of being in the  top 7.45% of users).
Also, I decided that, to mark this occasion, I would move all of my code from Dropbox, which just seems like a very informal place to be hosting code, to github, which seems far more legitimate, plus offers a viewer with syntax highlighting for more languages than just Java. I will continue inlining the code here, but the links from the table will now all point to github.

Anyway, here is my code for problem 50, and hopefully I will solve 50 more in due time.
#include<stdio.h>
#include<stdlib.h>

int isPrime(int n) {
    if (n < 2 || n % 2 == 0) {
        return n == 2;
    }
    int i = 3;
    for (i = 3; i*i <= n; ++i) {
        if (n % i == 0) {
            return 0;
        }
    }
    return 1;
}

int partialSum(int* arr, int begin, int end) {
    int sum = 0;
    int i;
    for (i = begin; i < end; ++i) {
        sum += arr[i];
    }
    return sum;
}

int main(int argc, char** argv) {
    int ans = 0;
    int chainLength = 1;
    //78498 = pi^-1(1000000)
    int* primes = (int*)malloc(78498 * sizeof(int));
    int i = 2;
    int c = 0;
    //make list of primes
    for (i = 0; i < 1000000; ++i) {
        if (isPrime(i)) {
            primes[c] = i;
            ++c;
        }
    }
    int j;
    for (i = 0; i < 78498; ++i) {
        for (j = i+chainLength; j < 78498; ++j) {
            int temp = partialSum(primes,i,j);
            if (temp > 1000000) {
                break;
            }
            if (isPrime(temp)) {
                ans = temp > ans ? temp : ans;
                chainLength = j - i;
            }
        }
    }
    printf("%d\n",ans);
    return 0;
} 

No comments:

Post a Comment