I tried an automatic Picat style translation into some higher order loop construct. And then a manual inlining of the higher order loop construct. The input to the automatic Picat style translation was:
:- table p/2.
p(0)=1 => !.
p(N)=Z =>
Z=0, K=1,
M is K*(3*K-1)//2,
while(M=<N,
(Z:=Z-(-1)^K*p(N-M),
K:=K+1,
M:=K*(3*K-1)//2)),
K:=1,
M:=K*(3*K+1)//2,
while(M=<N,
(Z:=Z-(-1)^K*p(N-M),
K:=K+1,
M:=K*(3*K+1)//2)).
A link to the code of the translator is found at the end of this answer. The automatic translator gave me:
?- listing(p_a/2).
% example2.pl
:- sys_notrace p_a/2.
p_a(0, 1) :-
!.
p_a(N, A) :-
Z = 0,
K = 1,
M is K*(3*K-1)//2,
while([B, C, D, E]\[F, C, G, H]\(G is D- -1^E*p(C-B),
H is E+1,
F is H*(3*H-1)//2), [I, J, _, _]\(I =< J), [M, N, Z,
K], [_, N, L, _]),
O is 1,
P is O*(3*O+1)//2,
while([Q, R, S, T]\[U, R, V, W]\(V is S- -1^T*p(R-Q),
W is T+1,
U is W*(3*W+1)//2), [X, Y, _, _]\(X =< Y), [P, N, L,
O], [_, N, A, _]).
It uses arithmetic function evaluation p(C-B) and p(R-Q). In my Prolog system arithmetic function evaluation uses the native Java stack, and I cannot evaluate 6666:
% ?- p(100,X).
% X = 190569292
% ?- p(6666,X).
% java.lang.StackOverflowError
% at jekpro.reference.arithmetic.EvaluableElem.moniEvaluate(EvaluableElem.java:207)
Also the use of while/4 meta predicate is a little slow. So I massaged the code, eliminate the arithmetic function evaluation and inlined while/4. I also used a poor mans tabling, which is a little faster:
:- thread_local p_cache/2.
p_manual(N, X) :- p_cache(N, X), !.
p_manual(0, 1) :-
!, assertz(p_cache(0, 1)).
p_manual(N, A) :-
Z = 0,
K = 1,
M is K*(3*K-1)//2,
p21([M, N, Z, K], [_, N, L, _]),
O is 1,
P is O*(3*O+1)//2,
p22([P, N, L, O], [_, N, A, _]),
assertz(p_cache(N, A)).
p21([B, C, D, E], O1) :- B =< C, !,
L is C-B,
p_manual(L, M),
G is D- -1^E*M,
H is E+1,
F is H*(3*H-1)//2,
p21([F, C, G, H], O1).
p21(I1, I1).
p22([Q, R, S, T], O2) :- Q =< R, !,
L is R-Q,
p_manual(L, M),
V is S- -1^T*M,
W is T+1,
U is W*(3*W+1)//2,
p22([U, R, V, W], O2).
p22(I2, I2).
Now things started looking good. The 2.743 seconds went down to:
/* SWI-Prolog 8.3.21 */
?- time(p_manual(6666,X)).
% 4,155,198 inferences, 0.879 CPU in 0.896 seconds (98% CPU, 4729254 Lips)
X = 193655306161707661080005073394486091998480950338405932486880600467114423441282418165863.
/* Jekejeke Prolog 1.5.0 */
?- time(p_manual(6666,X)).
% Up 736 ms, GC 20 ms, Threads 714 ms (Current 04/14/21 02:16:45)
X = 193655306161707661080005073394486091998480950338405932486880600467114423441282418165863
Open source:
Picat Style Scripting Translator II
https://gist.github.com/jburse/8a24fe5668960c8889770f40c65cdf35#file-picat2-pl
Picat Style Scripting Examples II
https://gist.github.com/jburse/8a24fe5668960c8889770f40c65cdf35#file-example2-pl
Picat Style Scripting Inlined
https://gist.github.com/jburse/8a24fe5668960c8889770f40c65cdf35#file-tune-pl