a-conjecture-of-mine

An exercise on polyglossy: the same problem solved on multiple languages

Commit
f4a708aee096ffa86edbcfc1a5d4ce037aeb1d1a
Parent
0dcbc80f01565bfc3adaff579fd56d3aaae7ab5e
Author
Pablo Escobar Gaviria <gark.garcia@protonmail.com>
Date

Improved all implementations in functional programming languages by make the calculation of the sum of the digits of the test values tail recursive.

Diffstat

2 files changed, 11 insertions, 10 deletions

Status File Name N° Changes Insertions Deletions
Modified Elixir/main.ex 15 8 7
Modified script.pl 6 3 3
diff --git a/Elixir/main.ex b/Elixir/main.ex
@@ -59,18 +59,19 @@ defmodule Conjecture do
     case :ets.lookup(:sums_cache, n) do
       [{_, sum_n}] -> sum_n
       [] ->
-        sum_n = sum n
+        sum_n = sum_digits n
         :ets.insert(:sums_cache, {n, sum_n})
         sum_n
     end
   end
 
-  def sum 0 do 0 end
+  def sum_digits n do sum_digits_tail n, 0 end
 
-  def sum n do
-    d = rem n, 10
-    r = div n, 10
+  def sum_digits_tail 0, acc do acc end
 
-    d + sum r
-  end
+  def sum_digits_tail n, acc do
+    r = rem n, 10
+    d = div n, 10
+    sum_digits_tail d, (acc + r)
+  end 
 end
diff --git a/script.pl b/script.pl
@@ -3,10 +3,10 @@
 % Let S: N -> N be the sum of the digits of a positive integer.
 % For all A and B in N, S(A + B) = S(A) + S(B) - 9k, where k is an integer.
 
-sum_digits(X, Y) :- sum_digits(X, 0, Y).
+sum_digits(X, Y) :- sum_digits_tail(X, 0, Y).
 
-sum_digits(X, Acc, Y) :- X < 10, !, Y is Acc + X.
-sum_digits(X, Acc, Y) :-
+sum_digits_tail(X, Acc, Y) :- X < 10, !, Y is Acc + X.
+sum_digits_tail(X, Acc, Y) :-
     Q = X div 10,
     R = X mod 10,
     Acc1 = Acc + R,