爲了好玩,我一直在用C++實現一些數學方面的東西,而且我一直試圖實現Fermats Factorisation Method,但是,我不知道我明白它應該返回什麼。我有這個實現,返回105
對於維基百科文章中給出的示例編號5959。Fermat的因式分解C++
在維基百科中的僞像這樣:
一個嘗試的各種值,希望是一個正方形。
FermatFactor(N): // N should be odd
a → ceil(sqrt(N))
b2 → a*a - N
while b2 isn't a square:
a → a + 1 // equivalently: b2 → b2 + 2*a + 1
b2 → a*a - N // a → a + 1
endwhile
return a - sqrt(b2) // or a + sqrt(b2)
我的C++實現,像這樣:
int FermatFactor(int oddNumber)
{
double a = ceil(sqrt(static_cast<double>(oddNumber)));
double b2 = a*a - oddNumber;
std::cout << "B2: " << b2 << "a: " << a << std::endl;
double tmp = sqrt(b2);
tmp = round(tmp,1);
while (compare_doubles(tmp*tmp, b2)) //does this line look correct?
{
a = a + 1;
b2 = a*a - oddNumber;
std::cout << "B2: " << b2 << "a: " << a << std::endl;
tmp = sqrt(b2);
tmp = round(tmp,1);
}
return static_cast<int>(a + sqrt(b2));
}
bool compare_doubles(double a, double b)
{
int diff = std::fabs(a - b);
return diff < std::numeric_limits<double>::epsilon();
}
它是什麼應該返回?它似乎只是返回a + b
,這不是因爲5959
?
EDIT
double cint(double x){
double tmp = 0.0;
if (modf(x,&tmp)>=.5)
return x>=0?ceil(x):floor(x);
else
return x<0?ceil(x):floor(x);
}
double round(double r,unsigned places){
double off=pow(10,static_cast<double>(places));
return cint(r*off)/off;
}
'static_cast(b2)'?有沒有原因在那裏?另外'compare_doubles'是如何定義的? –
jli
@jli'b2'是我早期實現的'int',讓我改變它,它沒有更多理由存在 –
我會爲'tmp'和'b2'使用整數類型。爲了讓測試通過,無論如何你都需要一個整數平方根「b2」。實際上,所有局部變量的ints實現都返回101. :) – vhallac