Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // main.c
- // Prime
- //
- // Created by Samon Hazrati on 9/4/15.
- // Copyright (c) 2015 Samon Hazrati. All rights reserved.
- //
- #include <stdio.h>
- #include <stdlib.h>
- #define SQRTPRIME 324
- #define NUMPRIMES 10000
- #define SIZE 104732
- //Function to determine primes using sieves, returns pointer to integer array
- int *primeFunc(void){
- //Number array is an array of numbers from 1 to SIZE, final array is storage; the rest are counters
- int *numberArray, *finalArr, i, j, k;
- //dynamically allocate arrays
- numberArray = malloc(sizeof(int)*SIZE);
- finalArr = malloc(sizeof(int)*NUMPRIMES);
- //set numberArray to zero
- for(i = 0; i < SIZE; i++)
- numberArray[i] = 0;
- //initialize k to 0
- k = 0;
- //checks until the sqaureroot of SIZE, which is the largest possible prime for a given set
- for(i = 2; i < SQRTPRIME; i++){
- //if the number at i is not flagged, flag every multiple of the number
- if(numberArray[i] == 0){
- for(j = 2i; j < SIZE; j += i){
- numberArray[j] = 1;
- }
- //store the original unflagged number into the prime array
- finalArr[k++] = i;
- }
- }
- //free duynamic array
- free(numberArray);
- //return pointer to integer array
- return finalArr;
- }
- int main(int argc, const char * argv[]) {
- int *primes, numberCases, x, i, sum;
- //initializes primes as the return of the primeFunc
- primes = primeFunc();
- //scan number of cases
- scanf("%d", &numberCases);
- //scan in the index of primes that needs to be summed
- for(i = 0; i < numberCases; i++){
- scanf("%d", &x);
- //reset sum for each loop
- sum = 0;
- //decerements x as a counter for the summing of the primes
- while(--x >= 0){
- sum += primes[x];
- }
- //prints sum for every for loop iteration
- printf("%d\n", sum);
- }
- //frees dynamically allocated array
- free(primes);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement