a-conjecture-of-mine

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

Commit
04c9f23dbc51a6e4850c4928c0c055dc05b7b4a0
Parent
7748222fd469bae042da905a01382047dee99923
Author
Gark Garcia <37553739+GarkGarcia@users.noreply.github.com>
Date

Further optimized the Prolog implementation.

Thanks to the awesome help of @flunschlik @wellmeaningtroll on redit the Prolog implementation is now much cleaner, more optimized and ideomatic. Check out the discussion in https://www.reddit.com/r/prolog/comments/ct266d/error_stack_limit_10gb_exceeded_help/.

Diffstat

1 file changed, 15 insertions, 22 deletions

Status File Name N° Changes Insertions Deletions
Modified script.pl 37 15 22
diff --git a/script.pl b/script.pl
@@ -3,34 +3,27 @@
 % 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_acc(X, X, A) :- X < 10, A is 0, !.
-sum_digits_acc(X, Y, A) :-
-    X >= 10,
-    X1 is div(X, 10),
-    X2 is mod(X, 10),
-    sum_digits_acc(X1, A, _),
-    Y is A + X2.
+sum_digits(X, Y) :- sum_digits_acc(X, 0, Y).
 
-sum_digits(X, Y) :- sum_digits_acc(X, Y, _).
+sum_digits_acc(X, A, Y) :- X < 10, !, Y is A + X.
+sum_digits_acc(X, A, Y) :-
+    Q  = X div 10,
+    R  = X mod 10,
+    A2 = A + R,
+    sum_digits_acc(Q, A2, Y).
 
 test_pair(A, B) :-
-    R is 0,
-    AB is A + B,
+    R  = 0,
+    AB = A + B,
     sum_digits(A, SA),
     sum_digits(B, SB),
     sum_digits(AB, SC),
-    SAB is SA + SB,
-    D is SC - SAB,
-    R is mod(D, 9).
+    SAB = SA + SB,
+    D   = SC - SAB,
+    R =:= D mod 9.
 
-iter(A, 0) :- test_pair(A, 0), !.
 iter(A, B) :-
-    test_pair(A, B),
-    C is B - 1,
-    iter(A, C).
+    forall(between(0, B, X), test_pair(A, X)).
 
-conjecture(0) :- test_pair(0, 0), !.
 conjecture(M) :-
-    iter(M, M),
-    N is M - 1,
-    conjecture(N).-
\ No newline at end of file
+    forall(between(0, M, X), iter(X, X)).+
\ No newline at end of file