recursive goldbach's conjecture


I've made a set of prime numbers and I'm trying to find the prime numbers that make up the number inputted into the function (goldbach)

for reference, the partition is a vector that stores numbers that could be the primes that make up the inputted number, and the vector stores them in increasing order.

This code gives me a segmentation fault, so I'm wondering where I'm accessing bad memory.

say I have this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
bool prime_partition::find_partition(int number, int terms=0){


  if(terms > max_terms){
    return false;
  }
  for(int i = 0; i < partition.size(); i++){
    if(partition.at(i) > partition.at(i+1)){
      return false;
    }
  }
  if(number == 0){
    return true;
  }


	set<int>::iterator start_it = pset.lower_bound((int)(sqrt(number))); 
	set<int>::iterator end_it = pset.upper_bound(number);

  
  while(start_it != end_it){

    partition.push_back(*start_it);

    if(find_partition(number-(*start_it), terms + 1)){
      return true;
    }

    partition.pop_back();
    start_it++;
  }

	return false;
}




1
2
  for(int i = 0; i < partition.size(); i++){
    if(partition.at(i) > partition.at(i+1))
Won't this throw an exception once i == partition.size() - 1?
oh because the next element is NULL, so i should handle that... Thanks for the pointer Ganado
Apologies for the pedantry, but just to correct the concepts here: The next element isn't NULL. The next element, partition.at(i+1), simply doesn't exist when we're at the final iteration. The .at() does bounds checking, which will throw an exception and avoid the undefined behavior associated with out-of-bounds array access.
Topic archived. No new replies allowed.