summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--AlgoDesignAndTechniqueEdxJava/sources/DifferentSummands.java39
-rw-r--r--AlgoDesignAndTechniqueEdxJava/tests/DifferentSummandsTest.java37
2 files changed, 76 insertions, 0 deletions
diff --git a/AlgoDesignAndTechniqueEdxJava/sources/DifferentSummands.java b/AlgoDesignAndTechniqueEdxJava/sources/DifferentSummands.java
new file mode 100644
index 0000000..1be417c
--- /dev/null
+++ b/AlgoDesignAndTechniqueEdxJava/sources/DifferentSummands.java
@@ -0,0 +1,39 @@
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Scanner;
+
+public class DifferentSummands {
+
+ public static void main(String[] args) {
+ Scanner scanner = new Scanner(System.in);
+ int n = scanner.nextInt();
+ List<Integer> summands = getOptimalSummands(n);
+ System.out.println(summands.size());
+ for (Integer summand : summands) {
+ System.out.print(summand + " ");
+ }
+ }
+
+ public static List<Integer> getOptimalSummands(int n) {
+ List<Integer> summands = new ArrayList<Integer>();
+ if (n < 3) {
+ summands.add(n);
+ return summands;
+ }
+ int runningSum = 0;
+ for (int i = 1; i < n + 1; i++) {
+ runningSum = runningSum + i;
+ summands.add(i);
+ if (runningSum == n) {
+ break;
+ }
+ if (runningSum > n) {
+ summands.remove(summands.size() - 1);
+ summands.set(summands.size() - 1, summands.get(summands.size() - 1).intValue() + n - runningSum + i);
+ break;
+ }
+ }
+ return summands;
+ }
+
+}
diff --git a/AlgoDesignAndTechniqueEdxJava/tests/DifferentSummandsTest.java b/AlgoDesignAndTechniqueEdxJava/tests/DifferentSummandsTest.java
new file mode 100644
index 0000000..5732642
--- /dev/null
+++ b/AlgoDesignAndTechniqueEdxJava/tests/DifferentSummandsTest.java
@@ -0,0 +1,37 @@
+import static org.junit.jupiter.api.Assertions.*;
+
+import org.junit.jupiter.api.Test;
+
+class DifferentSummandsTest {
+
+ @Test
+ void test() {
+ int n = 6;
+ assertEquals(3, DifferentSummands.getOptimalSummands(n).size());
+ }
+
+ @Test
+ void test1() {
+ int n = 8;
+ assertEquals(3, DifferentSummands.getOptimalSummands(n).size());
+ }
+
+ @Test
+ void test2() {
+ int n = 2;
+ assertEquals(1, DifferentSummands.getOptimalSummands(n).size());
+ }
+
+ @Test
+ void test3() {
+ int n = 4;
+ assertEquals(2, DifferentSummands.getOptimalSummands(n).size());
+ }
+
+ @Test
+ void test4() {
+ int n = 4;
+ assertEquals(3, DifferentSummands.getOptimalSummands(n).get(1).intValue());
+ }
+
+}