Digital root: Difference between revisions

Add solutions for Crystal
(Added PL/M)
(Add solutions for Crystal)
Line 1,300:
588225: root = 3, persistence = 2
9992: root = 2, persistence = 3</pre>
 
=={{header|Crystal}}==
 
If you just want the digital root, you can use this, which is almost 100x faster than calculating it with persistence:
<lang ruby>
def digital_root(n : Int, base = 10) : Int32
max_single_digit = base - 1
n = n.abs
if n > max_single_digit
n = 1 + (n - 1) % max_single_digit
end
n
end
</lang>
 
The faster approach when calculating it with persistence uses exponentiation and log to avoid converting to and from strings.
<lang ruby>
def digital_root_with_persistence(n : Int) : {Int32, Int32}
n = n.abs
persistence = 0
 
until n <= 9
persistence += 1
 
digit_sum = (0..(Math.log10(n).floor.to_i)).sum { |i| (n % 10**(i + 1) - n % 10**i) // 10**i }
 
n = digit_sum
end
 
{n, persistence}
end
</lang>
 
However, the string-conversion based solution is easiest to read.
<lang ruby>
def digital_root_with_persistence_to_s(n : Int) : {Int32, Int32}
n = n.abs
persistence = 0
 
until n <= 9
persistence += 1
 
digit_sum = n.to_s.chars.sum &.to_i
 
n = digit_sum
end
 
{n, persistence}
end
</lang>
 
=={{header|D}}==