【发布时间】:2011-09-21 08:37:13
【问题描述】:
我正在尝试使用fermats method 创建一个素数分解器。
此行产生错误
find_factors(A, B, FactorThis) when is_a_square(B) == true ->
对本地/导入函数 is_a_square/1 的调用在警卫中是非法的
我看到的唯一可能的替代方案是在函数中使用某种 case 语句。我正在避免这种情况,因为它可能会搞砸尾递归。我是一个 Erlang 菜鸟。 还有哪些其他方法可以实现此功能?
get_int_part_of_sqrt(N) ->
trunc(math:sqrt(N)).
is_a_square(N) ->
get_int_part_of_sqrt(N) * get_int_part_of_sqrt(N) == N.
calculate_new_b(A, FactorThis) ->
NewB = trunc(abs((A * A) - FactorThis)),
io:format("Calculate_new_b A^2 ~w- FT ~w= NB ~w ~n",[A*A,FactorThis,NewB]),
find_factors(A, B, FactorThis) when is_a_square(B) == true ->
io:format("find_factors true ~w ~w~n", [A, B]),
{ok, A + get_int_part_of_sqrt(B), A - get_int_part_of_sqrt(B)};
find_factors(A, B, FactorThis) ->
io:format("find_factors false ~w ~w~n", [A, B]),
NewA = A + 1,
NewB = calculate_new_b(NewA, FactorThis),
find_factors(NewA, NewB, FactorThis).
已编辑。 调用calculate_new_b时的固定参数
添加了缺少的 get_int_part_of_sqrts。
【问题讨论】:
标签: erlang