Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing divisibility of Ints by 11

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.

like image 436
marco Avatar asked Nov 27 '22 18:11

marco


2 Answers

A number x is divisible by y if it's remainder when divided by y is 0. So you can just do

divisibleBy11 x = x `rem` 11 == 0
like image 89
sepp2k Avatar answered Dec 09 '22 21:12

sepp2k


ifan I'm sure you know that in real life you would use mod or rem 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:

digits = map (`mod` 10) . takeWhile (> 0) . iterate (`div` 10)

divisible11 = (== 0) . head . dropWhile (>= 11) . iterate (reduce11 . digits)
  where
    reduce11 []     = 0
    reduce11 (d:ds) = foldl combine d $ zip (cycle [(-), (+)]) ds
    combine d (op, d') = d `op` d'
like image 32
Yitz Avatar answered Dec 09 '22 21:12

Yitz