Advertisement
Guest User

Untitled

a guest
Sep 4th, 2015
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.06 KB | None | 0 0
  1. //
  2. //  main.c
  3. //  Prime
  4. //
  5. //  Created by Samon Hazrati on 9/4/15.
  6. //  Copyright (c) 2015 Samon Hazrati. All rights reserved.
  7. //
  8.  
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #define SQRTPRIME 324
  12. #define NUMPRIMES 10000
  13. #define SIZE 104732
  14.  
  15.  
  16. //Function to determine primes using sieves, returns pointer to integer array
  17. int *primeFunc(void){
  18.     //Number array is an array of numbers from 1 to SIZE, final array is storage; the rest are counters
  19.     int *numberArray, *finalArr, i, j, k;
  20.    
  21.     //dynamically allocate arrays
  22.     numberArray = malloc(sizeof(int)*SIZE);
  23.     finalArr = malloc(sizeof(int)*NUMPRIMES);
  24.    
  25.     //set numberArray to zero
  26.     for(i = 0; i < SIZE; i++)
  27.         numberArray[i] = 0;
  28.    
  29.     //initialize k to 0
  30.     k = 0;
  31.    
  32.     //checks until the sqaureroot of SIZE, which is the largest possible prime for a given set
  33.     for(i = 2; i < SQRTPRIME; i++){
  34.         //if the number at i is not flagged, flag every multiple of the number
  35.         if(numberArray[i] == 0){
  36.             for(j = 2i; j < SIZE; j += i){
  37.                 numberArray[j] = 1;
  38.             }
  39.             //store the original unflagged number into the prime array
  40.             finalArr[k++] = i;
  41.            
  42.         }
  43.     }
  44.     //free duynamic array
  45.     free(numberArray);
  46.     //return pointer to integer array
  47.     return finalArr;
  48.    
  49. }
  50.  
  51. int main(int argc, const char * argv[]) {
  52.     int *primes, numberCases, x, i, sum;
  53.     //initializes primes as the return of the primeFunc
  54.     primes = primeFunc();
  55.     //scan number of cases
  56.     scanf("%d", &numberCases);
  57.     //scan in the index of primes that needs to be summed
  58.     for(i = 0; i < numberCases; i++){
  59.         scanf("%d", &x);
  60.         //reset sum for each loop
  61.         sum = 0;
  62.         //decerements x as a counter for the summing of the primes
  63.         while(--x >= 0){
  64.             sum += primes[x];
  65.         }
  66.         //prints sum for every for loop iteration
  67.         printf("%d\n", sum);
  68.      
  69.     }
  70.    
  71.     //frees dynamically allocated array
  72.     free(primes);
  73.    
  74.     return 0;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement