花和小時試圖找到一個錯誤,沒成功:(
解決歐拉問題:http://projecteuler.net/problem=35
看來我的頭此時不圓素,有助於發現錯誤,C++
工作代碼不是最優化的,對不起的是(我在做什麼錯在這裏?) 正確的答案是55,我的程序給我22個
#include "euler.hpp"
#include <algorithm>
int main() {
euler::prime_generator<euler::eratosthenes_sieve> gen;
gen.range(0, 1000000);
unsigned c = 0; // number of circular primes
unsigned p = 0; // number of primes (test)
unsigned prime;
while(prime = gen.nextPrime()) {
p++;
bool ok = true;
std::vector<unsigned> pv = euler::number2vector(prime);
if(pv.size() > 1) {
bool cont = false;
for(unsigned i = 0; i < pv.size(); ++i) {
if(pv[i] % 2 == 0) { cont = true; break; }
}
if(cont) continue;
std::sort(pv.begin(), pv.end());
do {
if(!gen.isPrime(euler::array2number(&pv[0], pv.size()))) {
// was desperate and made this
if(euler::isPrime(euler::array2number(&pv[0], pv.size()))) {
std::cout << prime << " -> " << euler::array2number(&pv[0], pv.size()) << std::endl;
}
else ok = false;
break;
}
} while(std::next_permutation(pv.begin(), pv.end()));
}
if(ok) {
//std::cout << prime << std::endl;
c++;
}
//std::cout << prime << std::endl;
}
std::cout << p << " -> " << c << std::endl;
euler::pause();
}
一些外部功能我用
// in class
void range(unsigned lower_bound, unsigned upper_bound) {
m_lower_bound = lower_bound;
primes.resize(upper_bound - lower_bound + 1, true);
for(unsigned i = 0; i < 2 - lower_bound; ++i) primes[i] = false;
for(unsigned i = 2; i <= sqrt(upper_bound - lower_bound); ++i) {
if(primes[i]) {
for(unsigned j = i*i; j <= upper_bound; j += i) {
primes[j] = false;
}
}
}
}
// in the same class
bool isPrime(unsigned number) {
return primes[number - m_lower_bound];
}
// in the same class
unsigned nextPrime() {
for(; next <= m_upper_bound; ++next) {
if(isPrime(next)) return next++ + m_lower_bound;
}
return 0;
}
template <typename T>
T array2number(T * begin, unsigned length) {
T number = 0;
unsigned m = 1;
while(length--) {
number += begin[length] * m;
m *= 10;
}
return number;
}
template <typename T>
std::vector<T> number2vector(T number) {
unsigned l = number_length(number);
std::vector<T> vec(l);
while(l--) {
vec[l] = number % 10;
number /= 10;
}
return vec;
}
預先感謝您!
試着縮小你的代碼到你認爲出錯的地方,大多數人不會閱讀你的整個代碼。 –
是的,我知道。但我重新檢查了每個功能。如果我不是那麼絕望的話,我將永遠不會在這裏發佈:(但是,謝謝你回答 –
問題是你的代碼有多長,在每個函數中添加小cout語句來觀察它正在做什麼。這是件枯燥的工作,但它會幫助調試你的程序 –