DEV Community

dev.to staff
dev.to staff

Posted on

Daily Challenge #132 - Is my friend cheating?

  • A friend of mine takes a sequence of numbers from 1 to n (where n > 0).
  • Within that sequence, he chooses two numbers, a and b.
  • He says that the product of a and b should be equal to the sum of all numbers in the sequence, excluding a and b.
  • Given a number n, could you tell me the numbers he excluded from the sequence?

The function takes the parameter: n (n is always strictly greater than 0) and returns an array or a string (depending on the language) of the form:

[(a, b), ...] or [[a, b], ...] or {{a, b}, ...} or or [{a, b}, ...]
with all (a, b) which are the possible removed numbers in sequence 1 to n.

[(a, b), ...] or [[a, b], ...] or {{a, b}, ...} or ...will be sorted in increasing order of the "a".

It happens that there are several possible (a, b). The function returns an empty array (or an empty string) if no possible numbers are found which will prove that my friend has not told the truth! (Go: in this case return nil).

Examples
removNb(26) should return [(15, 21), (21, 15)]
or
removNb(26) should return { {15, 21}, {21, 15} }
or
removeNb(26) should return [[15, 21], [21, 15]]
or
removNb(26) should return [ {15, 21}, {21, 15} ]
or
removNb(26) should return "15 21, 21 15"
or
in C:
removNb(26) should return **an array of pairs {{15, 21}{21, 15}}**
tested by way of strings.


This challenge comes from g964 on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!

Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!

Top comments (3)

Collapse
 
juanrodriguezarc profile image
Juan Rodríguez • Edited

function removeNb(n) {
  const arr = [...Array(n + 1).keys()]
  const acc = n*(n+1)/2;
  return Array.prototype.concat.apply([], arr.map(i => arr.map(x => [i,x]))) .filter(([a,b])=>  a * b == acc - a - b )
}

Collapse
 
mckkaleb profile image
Kaleb McKinney
def remove_number(number):
  sequence = []
  for i in range(number):
    sequence.append(number - i)
  index_one = 0
  index_two = 0
  while index_one < len(sequence):
    if sequence[index_one] * sequence[index_two] == sum(sequence) - (sequence[index_one] + sequence[index_two]):
      return [sequence[index_one], sequence[index_two]]
    if index_two < len(sequence) - 1:
      index_two += 1
    else:
      index_two = 1
      index_one += 1
  return []
Collapse
 
erezwanderman profile image
erezwanderman

JS

const removNb = n => Array(n).fill(undefined).map((_, i) => [i + 1, ((1 + n)*n/2 - i - 1) / (i + 2)]).filter(([a, b]) => b === ~~b && b <= n);