-3

Triangular numbers are numbers which is number of things when things can be arranged in triangular shape.

For Example, 1, 3, 6, 10, 15... are triangular numbers.

o

o o

o o o

o o o o

is shape of n=4 triangular number

what I have to do is A natural number N is given and I have to print N expressed by sum of triangular numbers.

if N = 4

output should be

1 1 1 1

1 3

3 1

else if N = 6

output should be

1 1 1 1 1 1

1 1 1 3

1 1 3 1

1 3 1 1

3 1 1 1

3 3

6

I have searched few hours and couldn't find answers...

please help.

(I am not sure this might help, but I found that

If i say T(k) is Triangular number when n is k, then

T(k) = T(k-1) + T(k-3) + T(k-6) + .... + T(k-p) while (k-p) > 0

and p is triangular number )

Here's Code for k=-1(Read comments below)

#include <iostream>
#include <vector>

using namespace std;

long TriangleNumber(int index);
void PrintTriangles(int index);

vector<long> triangleNumList(450); //(450 power raised by 2 is about 200,000)
vector<long> storage(100001);

int main() {
    int n, p;

    for (int i = 0; i < 450; i++) {
        triangleNumList[i] = i * (i + 1) / 2;
    }
    cin >> n >> p;
    cout << TriangleNumber(n);
    if (p == 1) {
        //PrintTriangles();
    }

    return 0;
}

long TriangleNumber(int index) {
    int iter = 1, out = 0;
    if (index == 1 || index == 0) {
        return 1;
    }
    else {
        if (storage[index] != 0) {
            return storage[index];
        }
        else {
            while (triangleNumList[iter] <= index) {
                storage[index] = ( storage[index] + TriangleNumber(index - triangleNumList[iter]) ) % 1000000;
                iter++;
            }
        }
    }
    return storage[index];
}
void PrintTriangles(int index) {
    // What Algorithm?
}
JRK
  • 23
  • 6
  • Since I am not pretty good at English, It would be very thankful to answers to be written in easy English.. – JRK Oct 07 '18 at 09:51
  • 1
    Maybe you share some of your ideas with US and Tell us where you got stuck. – sim Oct 07 '18 at 09:55
  • Your question is not completely clear. Do you want a *printout* of *all* the ways that `N` can be written as the sum of triangular numbers? Also, you show no real effort of your own. Don't search for an answer; write some code of your own and show us your attempt. That lets us know your level of programming. For example, do you understand recursion? (That was a hint but we do need to know that.) Finally, which computer language do you want? – Rory Daulton Oct 07 '18 at 10:04
  • @RoryDaulton Actually whole problem was N and k for input and if k = -1 just print how many ways can be expressed. if N=4 and k = -1 answer is 3. I Solved when k= -1 but i have no idea what algorithm to use when k = 1. I'll add my code soon. – JRK Oct 07 '18 at 10:06
  • k is just a flag whether i should print all combinations or just print how many. I am trying to add my code in my question, but it continuously says there is wrong format.... – JRK Oct 07 '18 at 10:17
  • @meowgoesthedog 4 = 1 +1+1+1 and it is also 1+3. elements should always be triangular numbers. – JRK Oct 07 '18 at 10:19
  • Oops I misread the question; should be easily doable using DP and memoization – meowgoesthedog Oct 07 '18 at 10:47
  • @RoryDaulton Thanks for advice. I have worked few more hours on it but I couldn't make any effort when k=1... Would you mind if you have look at my code and give some more advice? – JRK Oct 08 '18 at 05:54

1 Answers1

1

Here is some recursive Python 3.6 code that prints the sums of triangular numbers that total the inputted target. I prioritized simplicity of code in this version. You may want to add error-checking on the input value, counting the sums, storing the lists rather than just printing them, and wrapping the entire routine into a function. Setting up the list of triangular numbers could also be done in fewer lines of code.

Your code saved time but worsened memory usage by "memoizing" the triangular numbers (storing and reusing them rather than always calculating them when needed). You could do the same to the sum lists, if you like. It is also possible to make this more in the dynamic programming style: find the sum lists for n=1 then for n=2 etc. I'll leave all that to you.

""" Given a positive integer n, print all the ways n can be expressed as
the sum of triangular numbers.
"""
def print_sums_of_triangular_numbers(prefix, target):
    """Print sums totalling to target, each after printing the prefix."""
    if target == 0:
        print(*prefix)
        return
    for tri in triangle_num_list:
        if tri > target:
            return
        print_sums_of_triangular_numbers(prefix + [tri], target - tri)

n = int(input('Value of n ? '))

# Set up list of triangular numbers not greater than n
triangle_num_list = []
index = 1
tri_sum = 1
while tri_sum <= n:
    triangle_num_list.append(tri_sum)
    index += 1
    tri_sum += index

# Print the sums totalling to n
print_sums_of_triangular_numbers([], n)

Here are the printouts of two runs of this code:

Value of n ? 4
1 1 1 1
1 3
3 1

Value of n ? 6
1 1 1 1 1 1
1 1 1 3
1 1 3 1
1 3 1 1
3 1 1 1
3 3
6
Rory Daulton
  • 21,934
  • 6
  • 42
  • 50
  • 답변이 정말 도움이 많이 되었습니다. 제가 python을 깊게 배운것이 아니라 그런건지 잘 모르겠으나, 이것을 c++로 옮겨 작성하였을 때 이상한 결과를 도출해냅니다. 예를 들어, c++로 옮긴 코드에서 실행시켜보면 n = 6일 때 1 1 1 1

    1 1 1 1 3

    1 1 1 1 3 3 1

    이런식으로 출력이 됩니다. 재귀호출하면서 stack상에 어떠한 문제가 생긴것같은데, 왜 c++에서만 이런 문제가 발생하는지 잘 모르겠습니다.
    – JRK Oct 08 '18 at 19:47
  • The answer has really been a lot of help. I'm not sure if I'm learning python deeply, but I do not know if this is the case, but when I move it to c ++ I get strange results. For example, if you run in code that moves to c ++, when n = 6, 1 1 1 1

    1 1 1 1 3

    1 1 1 1 3 3 1

    code> Output. I have a recursive call, and I suspect that there is something wrong with the stack, but I do not know why it only happens in c ++. (translated version. Sorry for bad english.)

    – JRK Oct 08 '18 at 19:49
  • Thank you very much. what i missed was when using **print_sums_of_triangular_numbers(prefix + [tri], target - tri)** , I just pushed back vector and wrote like this **Function(pushedVec, target - tri)** . I solved by not pushing back but making another vector which is only for concating and send into Function. – JRK Oct 08 '18 at 20:36