【发布时间】:2015-03-03 17:26:33
【问题描述】:
我正在学习Erlang 和Joe 的书中指出的问题之一
如果 X 是偶数并且函数 even(X) 应该返回 true 否则为假。如果 X 是奇整数,则奇数 (X) 应返回真。
我解决这个问题的方法是
-module(math_functions).
%% API
-export([even/1, odd/1]).
even(Integer) -> (Integer >= 0) and (Integer rem 2 =:= 0).
odd(Integer) -> (Integer >= 1) and (Integer rem 2 =/= 0).
并将其运行为
Eshell V6.2 (abort with ^G)
1> math_functions:odd(13).
true
2> math_functions:odd(-13).
false
3> math_functions:odd(1).
true
4> math_functions:even(1).
false
5> math_functions:even(2).
true
6> math_functions:even(-2).
false
7>
我的问题是是否有更好的方法来做到这一点
谢谢
【问题讨论】:
-
为什么 -13 不是奇数而 -2 不是偶数?只是好奇。
-
我只对正整数这样做
-
你看过最低有效位法吗? Here 是 Erlang 示例的链接。
标签: erlang