DEV Community

Discussion on: Daily Challenge #183 - Automorphic Numbers

Collapse
 
craigmc08 profile image
Craig McIlwrath

Solution without strings (Haskell)

automorphic :: (Integral a) => a -> Bool
automorphic n = (n*n - n) `rem` (10 ^ digits) == 0
  where digits = (+1) $ floor $ logBase 10 $ fromIntegral n

An explanation: if n² ends in n, then n² - n ends in as many zeroes as there are digits in n. I'm not going to prove this here, I believe it is pretty straightforward. If a number ends in m zeroes, then the number is divisible (remainder of 0) by 10m.

The test now is: is n² - n divisible by 10 ^ (number of digits in n). Finding the number of digits is simple: the log base 10 of a number with m digits is m - x, x is in the interval (0,1]. This translates to floor(log base 10 of n) + 1 = number of digits.

So that's my solution.