p(n) = # Integer Partition
in
Programming Questions
•
2 years ago
I am copying (translating to Processing) an algorithm taken from:
http://www.numericana.com/answer/numbers.htm#partitions (the much faster one),
but I am getting the wrong results.
I should get p(n)=
1, 2, 3, 5, 7, 11, 15, 22, ...
but I get: 2, 6, 16, 44, 123, 340, 947, 2628, ...
What is wrong with my code? or is it the algorithm?
int pn(int n) {
// counting partition(n)
int[] p = new int[n+1];
p[0] = 1;
for (int i=1; i<=n; i++) {
int j=1;
int k=1;
int s=0;
while (j>0) {
j = i-(3*k*k+k)/2;
if (j>=0) {
s = s - ((-1)^k)*p[j];
}
j = i-(3*k*k-k)/2;
if (j>=0) {
s = s - ((-1)^k)*p[j];
}
k = k+1;
}
p[i] = s;
}
return p[n];
}
// counting partition(n)
int[] p = new int[n+1];
p[0] = 1;
for (int i=1; i<=n; i++) {
int j=1;
int k=1;
int s=0;
while (j>0) {
j = i-(3*k*k+k)/2;
if (j>=0) {
s = s - ((-1)^k)*p[j];
}
j = i-(3*k*k-k)/2;
if (j>=0) {
s = s - ((-1)^k)*p[j];
}
k = k+1;
}
p[i] = s;
}
return p[n];
}
1
