user20507295
user20507295

Reputation:

Additive and Multiplicative Combinations

Help! I am in dire need of help. I have a question given by a teacher and I need an answer! The question goes something along the lines of

Basically you have to enter a positive number that is greater than 1. After entering, the output would various numbers that add up to the number 6 (Example)

Example: Input: 7

Output: The combinations (1, 6), (4, 3), (3, 4), (6, 1), (5,2) (2,5). output

I tired nothing worked

Upvotes: 0

Views: 170

Answers (1)

GM_
GM_

Reputation: 145

Algorithm:

O(N^2) method:

  1. Create an empty array in javascript.
  2. Loop from (1,n) where 'i' would be the iterator and nest another (i, n) loop where j would be the iterator.
  3. If i+j = n then push (i,j) in the array.

let n = 7;
const res = [];
for(let i = 0 ; i < n; i++){
    for(let j = i; j < n ; j++ ){
        if(i+j == n) {
            res.push({i,j}, {j, i});
        }
    }
}
console.log(res);

Upvotes: 1

Related Questions