Saturday, April 28, 2012

Project Euler, Problem 7 solution

( http://projecteuler.net/problem=7 )
"Problem 7
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?"

Sure, I've written my stupid solution in C.
But after that I've discovered that the solution in J language can be done only with ONE line of code:
p: 10000
Amazing!

Btw. here is the C solution:
#include <stdio.h>
int main() {
    const int max = 10001;
    int count = 0;
    unsigned int i, j;

    for(i = 2; ; i++) {
        for(j = 2; j < i; j++) {
            if(i % j == 0)
                break;
        }
        if(i == j) {
            count++;
            if(count == max)
                break;
        }
    }
    printf("%dst prime number is: %d\n", max, i);
}

No comments:

Post a Comment