Answer the question
In order to leave comments, you need to log in
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);
}
}
}
}
Answer the question
In order to leave comments, you need to log in
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));
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question