problem 10 done, and problem 7 rewritten (new is_prime algorithm)
This commit is contained in:
parent
8498165fef
commit
2ba8a8aaeb
4 changed files with 64 additions and 36 deletions
47
p7.c
47
p7.c
|
|
@ -5,50 +5,25 @@
|
|||
* Projecteuler - Problem 7
|
||||
* ------------------------
|
||||
* 2009-12-28 Henrik Hautakoski
|
||||
*
|
||||
* fast and elegant solution using The fundamental theorem of arithmetic wich state:
|
||||
* any natural number greater than 1 can be prime factorized in only one unique way
|
||||
* unless it is prime itself.
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include <malloc.h>
|
||||
|
||||
int isprime(int *pl, int l, int p) {
|
||||
|
||||
int i;
|
||||
|
||||
for(i=0; i < l; i++) {
|
||||
|
||||
if((p % pl[i]) == 0)
|
||||
return 0;
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
#include "lib/prime.h"
|
||||
|
||||
int main() {
|
||||
|
||||
int i, len = 3, *prime = malloc(sizeof(int)*10001);
|
||||
uint32_t i, p, n = 1;
|
||||
|
||||
if (prime == NULL)
|
||||
return 1;
|
||||
|
||||
prime[0] = 2;
|
||||
prime[1] = 3;
|
||||
prime[2] = 5;
|
||||
|
||||
for(i=6; len < 10001; i++) {
|
||||
|
||||
if(!isprime(prime, len, i))
|
||||
continue;
|
||||
|
||||
prime[len++] = i;
|
||||
}
|
||||
for(i=3; n < 10001; i+=2) {
|
||||
|
||||
printf("%i\n", prime[len-1]);
|
||||
|
||||
free(prime);
|
||||
if (!is_prime(i))
|
||||
continue;
|
||||
|
||||
p = i;
|
||||
n++;
|
||||
}
|
||||
|
||||
printf("%i\n", p);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue