The code I wrote a few days ago actually has many optimizations. The simplest thing is that you don't need to traverse the entire prime number array. For example, the given even number is 100, you only need to calculate the prime number range from 2 to 97. The prime number above 97 (such as 101) does not need to be involved in the calculation. In this way, we need to find the prime number closest to the given even number from the known prime number, and use the binary method. Therefore, we need to first extract the binary method into a template class for reuse:
# Pragma once
// T: the project type in the container
// Container: container. The value of the subscript [] (INT) must be provided.
Template <typename T, class container>
Class binarysearch {
Public:
// Search. If the search succeeds, the following value is returned. If the search fails, the value-1 is returned.
Static int execute (
Const container & container, // container
Int containersize, // total number of elements in the container
Const T & T, // value to be matched
Bool extract = true // exact match? If this parameter is set to false, the nearest value is returned if no value is found.
)
{
If (containersize <= 0)
Return-1;
Int low = 0, high = containersize-1, MIDD = 0;
While (low <= high ){
MIDD = (low + high)/2;
Const T & middvalue = container [MIDD];
If (t = middvalue)
Return MIDD;
If (T <middvalue)
High = MIDD-1;
Else
Low = MIDD + 1;
}
Return extract? -1: MIDD;
}
};
Next, modify the Verification Algorithm:
Class Goldbach {
Public:
Bool check (INT even, Int & prime1, Int & prime2 ){
If (even <= 2 | 0! = (Even % 2 ))
Throw STD: logic_error ("an even number greater than 2 is required ");
// Generate all prime numbers not less than even
Primes _. Generate (even );
// Find the prime number closest to even
Int nearindex = binarysearch <int, PRIMES >:: execute (primes _, static_cast <int> (primes _. getcount (), even, false );
// Traverse
For (INT I = 0; I <= nearindex; ++ I ){
For (Int J = nearindex; j> = 0; -- j ){
If (primes _ [I] + primes _ [J] = even ){
Prime1 = primes _ [I];
Prime2 = primes _ [J];
Return true;
}
}
}
Return false;
}
Const primes & getprime (void) const {return primes _;}
PRIVATE:
Primes primes _;
};