测试整数能否被 11 整除
我现在正在努力处理这段代码。我想判断一个整数是否能被11整除。据我所知,当一个整数的各位数字之和(一次+,一次-)能被11整除时,该整数就能被11整除。
例如:56518可以整除乘以 11,因为 8-1+5-6+5 = 11,并且 11 可以被 11 整除。
我如何在 Haskell 中写下这个?提前致谢。
I'm struggling with this code right now. I want to determine whether an integer is divsible by 11. From what I have read, an integer is divisible to 11 when the sum (one time +, one time -) of its digits is divisible by 11.
For example: 56518 is divisible by 11, because 8-1+5-6+5 = 11, and 11 is divisible by 11.
How can i write this down in Haskell? Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一个数字
x
可以被y
整除,如果它除以y
的余数是0。所以你可以这样做A number
x
is divisible byy
if it's remainder when divided byy
is 0. So you can just doifan 我确信您知道在现实生活中您会使用
mod
或rem
来完成这个简单的示例,但您所询问的算法很有趣。这是一种有趣的方法,强调 Haskell 的函数性质:ifan I'm sure you know that in real life you would use
mod
orrem
for this simple example, but the algorithm you are asking about is interesting. Here's a fun way to do it that emphasizes the functional nature of Haskell:当然,
div
和mod
更快,但为什么不呢?我假设问题是将数字转换为数字列表:56518
被转换为字符串"56518"
,并且字符串中的每个符号(每个数字)都被转换使用map (:[])
转换为字符串本身,此时我们有["5","6","5","1","8"],我们将每个单位数字字符串读取为整数值:
[5,6,5,1,8]
。完毕。现在我们可以这样计算数字之和:
cycle [1,-1]
生成一个无限列表[1, -1, 1, -1, ...]
,我们将其与反转的数字列表 (toDigit x
) 配对,并将每对的元素相乘。所以我们有[8, -1, 5, -6, 5]
及其总和。现在我们可以递归地做到这一点:
Surely,
div
andmod
are faster, but why not? I assume the problem is converting a number to a list of digits:56518
is converted to a String"56518"
, and each symbol in the string (every digit) is converted to a string itself withmap (:[])
, at this point we have["5","6","5","1","8"]
, and we read every single-digit string as an integer value:[5,6,5,1,8]
. Done.Now we can calculate the sum of digits this way:
cycle [1,-1]
makes an infinite list[1, -1, 1, -1, ...]
, which we pair with the reversed list of digits (toDigit x
), and multiply elements of every pair. So we have[8, -1, 5, -6, 5]
and its sum.Now we can do it recursively:
怎么样...
How about...