Advertisement
HwapX

Desafio Soma de primos

Nov 1st, 2015
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.79 KB | None | 0 0
  1. // http://www.forum-invaders.com.br/vb/showthread.php/42846-DESAFIO-Soma-de-primos
  2.  
  3. #include <stdio.h>
  4. #include <math.h>
  5. #include <windows.h>
  6.  
  7. #define BUFFER_SIZE 128
  8.  
  9. typedef struct {
  10.     int count;
  11.     int* primes;
  12. } primes_t;
  13.  
  14. primes_t* primesCreate() {
  15.     primes_t* a = malloc(sizeof(primes_t));
  16.     a->count = 1;
  17.     a->primes = malloc(sizeof(int) * BUFFER_SIZE);
  18.     a->primes[0] = 2;
  19.     return a;
  20. }
  21.  
  22. int isPrime(primes_t* a, int n)
  23. {
  24.     int s = sqrt(n) + 1;
  25.     int i;
  26.    
  27.     for(i = 0; i < a->count; ++i) {
  28.         if(a->primes[i] > s)
  29.             return 1;
  30.         if(n % a->primes[i] == 0)
  31.             return 0;
  32.     }
  33.  
  34.     return 1;
  35. }
  36.  
  37. void primesMake(primes_t* a) {
  38.     if(a->count % BUFFER_SIZE)
  39.         a->primes = realloc(a->primes, sizeof(int) * BUFFER_SIZE * (int)((a->count / BUFFER_SIZE) + 1));
  40.        
  41.     int i = a->primes[a->count - 1];
  42.     while(!isPrime(a, ++i));
  43.     a->primes[a->count++] = i;
  44. }
  45.  
  46. void primesDestroy(primes_t* a) {
  47.     free(a->primes);
  48.     free(a);
  49. }
  50.  
  51. int zaz(primes_t* a, int v, int i, int f) {
  52.     int c = 0;
  53.     for(; i < a->count; ++i) {
  54.         int r = v - a->primes[i];
  55.         if(r > 0)
  56.             c += zaz(a, r, i, 0);
  57.         else if(r == 0 && f == 0) {
  58.             return ++c;
  59.         } else
  60.             return c;
  61.     }
  62.    
  63.     return c;
  64. }
  65.  
  66. int main(int argc, char **argv)
  67. {
  68.     unsigned int s = GetTickCount();
  69.     int n = 1;
  70.     int c = 0;
  71.     primes_t* a = primesCreate();
  72.    
  73.     do {
  74.         ++n;
  75.         while(n > a->primes[a->count - 1] + 1)
  76.             primesMake(a);
  77.     } while((c = zaz(a, n, 0, 1)) < 5000);
  78.    
  79.     primesDestroy(a);
  80.    
  81.     unsigned int e = GetTickCount() - s;
  82.    
  83.     printf("result %d %d\n", c, n);
  84.     printf("elapsed %d milliseconds", e);
  85.     return 0;
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement