It's well known that any positive number can be expressed through at most 3 Triangular numbers. ( https://oeis.org/A000217 )
Example:
11 := 10 + 1
12 := 10 + 1 + 1
13 := 10 + 3
14 := 10 + 3 + 1
15 := 15
I am searching the representation of the positive number n
through at most 3 possible Triangular summands. There can exist more than one representation of n
. I am interested in the one with the greatest summands.
Is there a more effective way than 2 decreasing for and 1 increasing for loops to find the summands?
public void printMaxTriangularNumbers(int n){
int[] tri = createTriangularNumbers(1000);
lbl: for(int i = tri.length-1; ; i--){
int tmp = n - tri[i];
if(tmp == 0){
System.out.println(tri[i]);
break;
}
for(int j=i; j>0; j--){
int tmp2 = tmp - tri[j];
if(tmp2 ==0){
System.out.println(tri[i]);
System.out.println(tri[j]);
break lbl;
}
for(int k=1; k <= j;k++){
if(tmp2 - tri[k] == 0){
System.out.println(tri[i]);
System.out.println(tri[j]);
System.out.println(tri[k]);
break lbl;
}
}
}
}
}
public int[] createTriangularNumbers(int n){
int[] out = new int[n+1];
for(int i=1,sum=0; i<=n;i++){
out[i] = sum += i;
}
return out;
}