【发布时间】:2012-05-15 11:51:30
【问题描述】:
为了好玩,我一直在用 C++ 实现一些数学知识,并且一直在尝试实现 Fermats Factorisation Method,但是,我不知道我理解它应该返回什么。我有这个实现,返回105 用于维基百科文章中给出的示例编号 5959。
维基百科中的伪代码如下所示:
尝试不同的 a 值,希望它是一个正方形。
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的因素?
编辑
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<double>(b2)?有什么原因吗?还有compare_doubles是怎么定义的? -
@jli
b2在我之前的实现中是一个int,让我改变它,它没有存在的理由 -
我会为
tmp和b2使用整数类型。为了使测试通过,无论如何您都需要一个整数平方根b2。事实上,所有局部变量的整数实现都返回 101。:) -
什么是二元轮函数?
标签: c++ math factorization