How to resolve the algorithm Partition function P step by step in the Prolog programming language
How to resolve the algorithm Partition function P step by step in the Prolog programming language
Table of Contents
Problem Statement
The Partition Function P is the function P(n), where n∈ℤ, defined as the number of distinct ways in which n can be expressed as the sum of non-increasing positive integers.
P(n) can be expressed as the recurrence relation: The successive numbers in the above equation have the differences: 1, 3, 2, 5, 3, 7, 4, 9, 5, 11, 6, 13, 7, 15, 8 ... This task may be of popular interest because Mathologer made the video, The hardest "What comes next?" (Euler's pentagonal formula), where he asks the programmers among his viewers to calculate P(666). The video was viewed more than 100,000 times in the first couple of weeks after its release. In Wolfram Language, this function has been implemented as PartitionsP.
Write a function which returns the value of PartitionsP(n). Solutions can be iterative or recursive. Bonus task: show how long it takes to compute PartitionsP(6666).
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Partition function P step by step in the Prolog programming language
Source code in the prolog programming language
/* SWI-Prolog 8.3.21 */
/* Author: Jan Burse */
:- table p/2.
p(0, 1) :- !.
p(N, X) :-
aggregate_all(sum(Z), (between(1,inf,K), M is K*(3*K-1)//2,
(M>N, !, fail; L is N-M, p(L,Y), Z is (-1)^K*Y)), A),
aggregate_all(sum(Z), (between(1,inf,K), M is K*(3*K+1)//2,
(M>N, !, fail; L is N-M, p(L,Y), Z is (-1)^K*Y)), B),
X is -A-B.
?- time(p(6666,X)).
% 13,962,294 inferences, 2.610 CPU in 2.743 seconds (95% CPU, 5350059 Lips)
X = 1936553061617076610800050733944860919984809503384
05932486880600467114423441282418165863.
You may also check:How to resolve the algorithm Möbius function step by step in the jq programming language
You may also check:How to resolve the algorithm Zero to the zero power step by step in the Visual Basic .NET programming language
You may also check:How to resolve the algorithm Handle a signal step by step in the Erlang programming language
You may also check:How to resolve the algorithm Generic swap step by step in the AWK programming language
You may also check:How to resolve the algorithm Anagrams step by step in the Seed7 programming language