V
V
Vlad1612014-04-12 16:50:46
Java
Vlad161, 2014-04-12 16:50:46

Output 3 numbers that add up to the number n

Given a natural number n, it is known that it can be divided into the sum of 3 unequal 0 numbers.
Write a program that displays all these numbers, but they should not be repeated, that is, nothing should be output from changing the places of the terms, for example, the number 6, 1 + 2 + 3 and 2 + 2 + 2 should be displayed, here is my algorithm

int n = Integer.parseInt(reader.readLine());

        for (int i = 1; i < n; i++) {
            for (int j = 1; j < n; j++) {
                for (int k = 1; k < n; k++) {
                     if ((i+j+k) == n) {
                         System.out.println("Числа " + i + " + " + j + " + " +k);
                     }
                }
            }
        }

But it outputs:
Numbers 1 + 1 + 4
Numbers 1 + 2 + 3
Numbers 1 + 3 + 2
Numbers 1 + 4 + 1
Numbers 2 + 1 + 3
Numbers 2 + 2 + 2
Numbers 2 + 3 + 1
Numbers 3 + 1 + 2
Numbers 3 + 2 + 1
Numbers 4 + 1 + 1
I can't catch up how to check. You can write in java or c++, whichever is more convenient for you).
P.s. I forgot to say, the program should be solved only by variables and loops, that is, no collections, arrays, etc.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2014-04-12
@Vlad161

Permutations should not be repeated - this means that for each set of terms {a, b, c} it is possible to find a set {a', b', c'}, formed by a permutation of the elements of the original set, such that a'<=b'<=c' . This means that each next nested loop should start not from 1, but from the value of the iterator of the previous loop.
---
Another thought:
Given a<=b<=c , a+b+c=n , the value of a cannot be greater than n/3 , otherwise b or c will be less than a .
The value of b cannot be greater than (na)/2 , otherwise c will be b̶o̶l̶b̶sh̶e lessb .
The value of c will be equal to (nab) .
In total, we get

int n = Integer.parseInt(reader.readLine());
for (int i = 1; i <= n/3; i++) {
    for (int j = i; j <= (n-i)/2; j++) {
        System.out.println("Числа " + i + " + " + j + " + " + (n-i-j));
    }
}

A
Alexander Belov, 2014-04-12
@IPRIT

Banal n 3 will not work.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question