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
18
lib/prime.c
Normal file
18
lib/prime.c
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
|
||||
#include "prime.h"
|
||||
#include <math.h>
|
||||
|
||||
int is_prime(uint32_t p) {
|
||||
|
||||
uint32_t i, l;
|
||||
|
||||
if (p < 2 || (p & 1) == 0)
|
||||
return 0;
|
||||
|
||||
l = ((uint32_t)sqrt(p)) + 1;
|
||||
|
||||
for(i=3; i < l; i+=2)
|
||||
if (p % i == 0) return 0;
|
||||
|
||||
return 1;
|
||||
}
|
||||
10
lib/prime.h
Normal file
10
lib/prime.h
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
|
||||
#ifndef __PRIME_H
|
||||
|
||||
#define __PRIME_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
int is_prime(uint32_t p);
|
||||
|
||||
#endif /* __PRIME_H */
|
||||
25
p10.c
Normal file
25
p10.c
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
|
||||
/*
|
||||
* http://projecteuler.net
|
||||
*
|
||||
* Projecteuler - Problem 10
|
||||
* ------------------------
|
||||
* 2010-04-06 Henrik Hautakoski
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include "lib/prime.h"
|
||||
|
||||
int main() {
|
||||
|
||||
uint32_t i;
|
||||
uint64_t s = 2;
|
||||
|
||||
for(i=3; i < 2e6; i+=2) {
|
||||
if (is_prime(i))
|
||||
s += i;
|
||||
}
|
||||
printf("%lli\n", s); /* this format throws som warnings but works so whatever */
|
||||
|
||||
return 0;
|
||||
}
|
||||
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