0

I have a problem statement.

Given an even number A ( greater than 2 ), return two prime numbers whose sum will be equal to given number.

The following solution code runs fine for all small and medium inputs but fails for a very large input 16777214. It is a segmentation fault and I tried to read this article on it but I cannot figure out what my program is doing wrong, since it is working for other inputs or what should I fix here. I'm new to C++;

#include <iostream> 
#include <vector>
using namespace std; 

void form_sieve(int A, int* prime){
    for(int c = 0; c < A; c++)
        prime[c] = 1;
    prime[0] = 0;
    prime[1] = 0;
    for(int p = 2; p * p <= A; p++){
        if(prime[p] == 1){
            // update all multiples of p
            for(int i = p * p; i <= A; i += p)
                prime[i] = 0;
        }
    }
}

void primesum(int A) {
    // find prime numbers less than A
    // use sieve method
    int prime[A + 1];
    form_sieve(A, prime);
    vector<int> result;
    // for(int c = 0; c <= A; c++)
    //     cout << prime[c] << "\n";


    for(int i = 2; i <= A; i++){
        if(prime[i]){
            if(i + i == A){
                result.push_back(i);
                result.push_back(i);
                break;
            }
            else if(prime[A - i]){
                result.push_back(i);
                result.push_back(A - i);
                break;
            }
        }

    }
    // cout << result.size();
    for(vector<int>::iterator ptr =  result.begin(); ptr < result.end(); ptr++){
        cout << *ptr << "\n";
    }
    // return result;
}


// Driver Code 
int main() 
{ 
    primesum(16777214);
} 

HalfWebDev
  • 7,022
  • 12
  • 65
  • 103

1 Answers1

0

You need to allocate new memory.

A user2717954 already suggested using a vector for primes, which is the best way to fix this.

If you wanted to use arrays, you could change int prime[A+1] to int* prime = new int[A+1];. Then delete [] prime; after you're finished using it at the end of the function.

When I do this, the program doesn't segfault. You must allocate dynamic memory and clean up after you're done since the program doesn't know how much memory to allocate since the size A + 1 isn't known at compile-time.

However, vectors will, of course, resize as needed so you won't have to worry about dynamic memory.

cam
  • 4,409
  • 2
  • 24
  • 34