Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // http://www.forum-invaders.com.br/vb/showthread.php/42846-DESAFIO-Soma-de-primos
- #include <stdio.h>
- #include <math.h>
- #include <windows.h>
- #define BUFFER_SIZE 128
- typedef struct {
- int count;
- int* primes;
- } primes_t;
- primes_t* primesCreate() {
- primes_t* a = malloc(sizeof(primes_t));
- a->count = 1;
- a->primes = malloc(sizeof(int) * BUFFER_SIZE);
- a->primes[0] = 2;
- return a;
- }
- int isPrime(primes_t* a, int n)
- {
- int s = sqrt(n) + 1;
- int i;
- for(i = 0; i < a->count; ++i) {
- if(a->primes[i] > s)
- return 1;
- if(n % a->primes[i] == 0)
- return 0;
- }
- return 1;
- }
- void primesMake(primes_t* a) {
- if(a->count % BUFFER_SIZE)
- a->primes = realloc(a->primes, sizeof(int) * BUFFER_SIZE * (int)((a->count / BUFFER_SIZE) + 1));
- int i = a->primes[a->count - 1];
- while(!isPrime(a, ++i));
- a->primes[a->count++] = i;
- }
- void primesDestroy(primes_t* a) {
- free(a->primes);
- free(a);
- }
- int zaz(primes_t* a, int v, int i, int f) {
- int c = 0;
- for(; i < a->count; ++i) {
- int r = v - a->primes[i];
- if(r > 0)
- c += zaz(a, r, i, 0);
- else if(r == 0 && f == 0) {
- return ++c;
- } else
- return c;
- }
- return c;
- }
- int main(int argc, char **argv)
- {
- unsigned int s = GetTickCount();
- int n = 1;
- int c = 0;
- primes_t* a = primesCreate();
- do {
- ++n;
- while(n > a->primes[a->count - 1] + 1)
- primesMake(a);
- } while((c = zaz(a, n, 0, 1)) < 5000);
- primesDestroy(a);
- unsigned int e = GetTickCount() - s;
- printf("result %d %d\n", c, n);
- printf("elapsed %d milliseconds", e);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement