LinAGKar

LinAGPrime-C

Oct 12th, 2015
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.27 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int main(int argc, char* argv[]) {
  5.     if(argc < 2) {
  6.         fprintf(stderr, "Must specify max, e.g. \"%s 10000000\"\n", argv[0]);
  7.         return -1;
  8.     } else if(argc > 2) {
  9.         fprintf(stderr, "Too many arguments\n");
  10.         return -1;
  11.     }
  12.  
  13.     const int MAX = atoi(argv[1]); // Programmet hittar all primtal under MAX
  14.  
  15.     int len_allocated = 8;
  16.     int* primes = malloc(len_allocated * sizeof(int));
  17.     int* primes_square = malloc(len_allocated * sizeof(int));
  18.  
  19.     if(primes == NULL || primes_square == NULL) {
  20.         fprintf(stderr, "Failed to allocate memory\n");
  21.         exit(EXIT_FAILURE);
  22.     }
  23.  
  24.     int len = 0;
  25.  
  26.     int i;
  27.     for(i = 2; i < MAX; i++) {
  28.         int divisible = 0;
  29.  
  30.         int j;
  31.         for(j = 0; j < len; j++) {
  32.             if(primes_square[j] > i) {
  33.                 break;
  34.             }
  35.             if(!(i % primes[j])) {
  36.                 divisible = 1;
  37.                 break;
  38.             }
  39.         }
  40.  
  41.  
  42.         if(!divisible) {
  43.             if(len >= len_allocated) {
  44.                 len_allocated *= 2;
  45.                 if((primes = realloc(primes, len_allocated * sizeof(int))) == NULL || (primes_square = realloc(primes_square, len_allocated * sizeof(int))) == NULL) {
  46.                     fprintf(stderr, "Failed to allocate memory\n");
  47.                     exit(EXIT_FAILURE);
  48.                 }
  49.             }
  50.             primes[len] = i;
  51.             primes_square[len] = i * i;
  52.             len++;
  53.             printf("%d\n", i);
  54.         }
  55.     }
  56.  
  57.     return 0;
  58. }
Advertisement
Add Comment
Please, Sign In to add comment